The javax.mail.Session object represents the session. It provides access to protocol implementations.
There are two alternative methods for obtaining a session object:
Using resource injection
This approach has been available since Java EE 5. It requires you to annotate the Session object as a resource with the corresponding alias. The system will locate the respective resource.
Note
This method is not applicable to JSP pages.
Using JNDI resource location
This is the classical approach. You can use it in all types of components.
Declare the Session object in the source code and add the @Resource annotation before it. In the name argument of the annotation, set the resource name.
Example
@Resource(name="mail/myMailSession") private javax.mail.Session session;
In the source code, look up the object using the javax.naming.InitialContext.
Example
InitialContext ctx = new InitialContext(); Session ses = (Session)ctx.lookup("java:comp/env/mail/MailSession");
Add the respective resource description in the web.xml, or ejb-jar.xml (depending on whether you are using the session object inside servlet/JSP, or EJB respectively).
Example
<resource-ref> <res-ref-name>mail/Session</res-ref-name> <res-type>javax.mail.Session</res-type> <res-auth>Container</res-auth> </resource-ref>