Sending an Email Using the JavaMail Session and Glassfish
This tutorial is a supplement to the article of oracle published here. After reading this later, I decided to share some tips about this EE environment JavaMail api configuration.
Two years ago, we decided to move to JEE 6 for our enterprise solutions and take a lot of fun with new EJB 3.1 features and annotations. Glassfish has made our lives easier, it was very easy to declare variables using it’s administration console. Less complicated than using global resource environment for properties It is also the continuation to this tricks this tutorial delegate to Glassfish EE server managing mail session.
- Before starting this tutorial, you should:
- Fully understand of http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.html
- Have access to an SMTP server. You must know the host name, port number, and security settings for your SMTP server. Web mail providers may offer SMTP access, view your email account settings or help to find further information. Be aware that your user name is often your full email address and not just the name that comes before the @ symbol.
- Have basic familiarity with Servlets and CDIs (helpful but not required)
Create a Java mail session resource :
To create and JavaMail Session :
- start galssfish server
- open admin console ( default localhost:4848)
- Go to Resources -> JavaMail Sessions -> click new to add new javaMail resource
- make sure the following field are filled in :
Jndi name : EMailME for example, will be used later on lookup resource :
- Default user
- Default sender will be used later on mailSession.getProperty(“mail.from”)
- For secure Mail add this advanced setting :
- mail.smtp.password : email password
- mail.smtp.port : email port
- mail.smtp.auth : true
This screenshot summarizes all these parameters :
II - Using email Service
This tutorial is a supplement to oracle one. We will use CDI with the same example.
- MailSessionBean Will be a CDI bean with RequestScope
- Inject the full JavaMail Session as resource rather than create it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Look short !
- EmailServlet remind the same except using @Inject rather than @EJB
1 2 3 4 5 6 7 8 9 10 11 12
Let’s EE Server manager MailSession for us, keep configuration on server and thanks to Glassfish administration console managing JavaMail Session became easier.