This tutorial will teach us how to send an email in Glassfish using JavaMail session injection. It use gmail for sending the email.
Steps:
1.) First we need to create a JavaMail session by, opening Glassfish admin: http://localhost:4848, and navigating to Resources->JavaMail Sessions.
2.) Click "New" button and input the following values:
JNDI Name: mailSession
Mail Host: smtp.gmail.com
Default User and Default Sender Address: any of your valid gmail account
3.) Leave Advance Setting unchange.
4.) On the Additional Properties section, we need to add the following properties:
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.password=yourPassword
mail.smtp.auth=true
mail.smtp.port=465
mail.smtp.socketFactory.port=465
5.) And finally a sample code that do the sending:
Steps:
1.) First we need to create a JavaMail session by, opening Glassfish admin: http://localhost:4848, and navigating to Resources->JavaMail Sessions.
2.) Click "New" button and input the following values:
JNDI Name: mailSession
Mail Host: smtp.gmail.com
Default User and Default Sender Address: any of your valid gmail account
3.) Leave Advance Setting unchange.
4.) On the Additional Properties section, we need to add the following properties:
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.password=yourPassword
mail.smtp.auth=true
mail.smtp.port=465
mail.smtp.socketFactory.port=465
5.) And finally a sample code that do the sending:
package com.czetsuya.demo;
import java.io.UnsupportedEncodingException;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.naming.NamingException;
/**
* @author Edward P. Legaspi
* @since Nov 18, 2012
**/
@Startup
@Singleton
public class StartupListener {
@Resource(name = "mailSession")
private Session mailSession;
@PostConstruct
private void init() throws NamingException, MessagingException,
UnsupportedEncodingException {
Message msg = new MimeMessage(mailSession);
msg.setSubject("Hello World!");
msg.setRecipient(RecipientType.TO, new InternetAddress(
"to@gmail.com", "czetsuya 2"));
msg.setFrom(new InternetAddress("from@gmail.com", "czetsuya 1"));
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Hello World!.");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
}
}
Post a Comment