Show TOC

Procedure documentationObtaining a Session Object Locate this document in the navigation structure

 

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 Note

    This method is not applicable to JSP pages.

    End of the note.
  • Using JNDI resource location

    This is the classical approach. You can use it in all types of components.

Procedure

Using Resource Injection

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 Example

  1. @Resource(name="mail/myMailSession")
    private javax.mail.Session session;
    
End of the code.
Using JNDI
  1. In the source code, look up the object using the javax.naming.InitialContext.

    Example Example

    1. InitialContext ctx = new InitialContext();
      Session ses = (Session)ctx.lookup("java:comp/env/mail/MailSession");
      
    End of the code.
  2. 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 Example

    1. <resource-ref>
            <res-ref-name>mail/Session</res-ref-name> 
            <res-type>javax.mail.Session</res-type>
            <res-auth>Container</res-auth>
      </resource-ref>
      
    End of the code.