0

Hi,

I am using the following code to send email using JSP through gmail.

But i am getting error in the following line:
Session mailSession = Session.getDefaultInstance(props, null);

String host="", user="", pass="";
host = smtp_server; //"smtp.gmail.com"; 
user = jsp_email; //"YourEmailId@gmail.com" // email id to send the emails
pass = jsp_email_pw; //Your gmail password
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
String to = "user@gmail.com"; // out going email id
String from = "user@gmail.com"; //Email id of the recipient
String subject = "subject";
String messageText = "body";
boolean sessionDebug = true;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol.", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setContent(messageText, "text/html"); // use setText if you want to send text
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, pass);
try {
transport.sendMessage(msg, msg.getAllRecipients());
out.println("Email sent");
WasEmailSent = true; // assume it was sent
}
catch (Exception err) {
WasEmailSent = false; // assume it's a fail
}
transport.close();

Does anyone else is also getting similar error?

Or do you have any better way to send email using jsp.

2
Contributors
1
Reply
4
Views
7 Years
Discussion Span
Last Post by eswaramoorthy
0

Hi, I check your code. its worked for me.

But, here i use two jar files : mail.jar and mailapi.jar

These two jar files i add in libraries.(Netbeans IDE6.7.1)
And little i test the mailSeesion object content using out.println(),

Session mailSession = Session.getDefaultInstance(props, null);
  out.println("mailSession : " + mailSession);

And,

try 
{
   transport.sendMessage(msg, msg.getAllRecipients());
   out.println("Email sent");
   //WasEmailSent = true; // assume it was sent 
}
catch (Exception err) 
{
   err.printStackTrace();
  //WasEmailSent = false; // assume it's a fail
}

Finally, after run i got mail (here i use From and to : use my gmail id).
The output:
mailSession : javax.mail.Session@1be9a50 Email sent.

Edited by eswaramoorthy: add one method

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.