• Entries (RSS)
  • Comments (RSS)

Sending an e-mail using WebSphere Mail session settings.

Posted by | Posted in WebSphere | Posted on 27-10-2008

Tagged Under : , , , ,

Sending an e-mail using WebSphere Mail session settings.

Yesterday I had posted about configuring a Mail Session in WebSphere Application Server admin console. Today I will be talking about sending an email from your JSP using the configured mail session.

To access the Mail session for sending your email you need to do a JNDI lookup from your JSP file. The complete code for sending email using the Mail Session settings is given below.

	// Look up mail session
	javax.naming.Context context = new javax.naming.InitialContext();
	javax.mail.Session mailSession = (javax.mail.Session) context.lookup("mail/localmail");
	javax.mail.Message msg = new javax.mail.internet.MimeMessage(mailSession);
	msg.setFrom(new javax.mail.internet.InternetAddress(fromEmail));
	msg.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(toEmail));
	msg.setSubject(mailSubject);
	msg.setText(mailBody);
 
	javax.mail.Transport.send(msg);
	System.out.println("Message Sent");

I have used the JNDI name directly for accessing the mail session settings. A better alternative is to use the resource reference in your JSP/Servlet code. The advantage of this approach is that we don’t need to alter the code even if our configuration name changes.

To add a resource reference opens your web.xml. Go to References Tab. Click on Add and select Resource Reference as the reference type and enter the details. For type select javax.mail.Session from the drop down box. If you are using resource reference, your lookup code will change to

	javax.mail.Session mailSession = (javax.mail.Session) context.lookup("java:comp/mail/localmail");

Share

Read More

Post a Comment