Search code examples
javasessionjakarta-eejakarta-mail

How to share the same email session between all instances of the application?


Maybe this question is already answered, but I couldn't find the proper answer. I have a web application based in JSF, and I want to share the same email session between all the instances of the application, yet I haven't found how to do that.

My questions are:

a) What I am thinking is stupid? Should I just create a new session every time that I want to send a new mail?

b) If a is false, is there a proper way to do that?

Additional info: I'm working with PrimeFaces 4.0, Apache Tomcat 7.0.41, and JDK 7.

EDIT: I'm establishing an email connection like this (using sun's java mail)

    Properties datos = new Properties();
    datos.put("mail.smtp.host", "smtp.gmail.com");
    datos.setProperty("mail.smtp.starttls.enable", "true");
    datos.setProperty("mail.smtp.port", "587");
    datos.setProperty("mail.smtp.user", usuarioAutenticacion);
    datos.put("mail.smtp.timeout", 5000);
    System.out.println(usuarioAutenticacion + " - " + contrasenaAutenticacion);
    sesionCorreo = Session.getDefaultInstance(datos, null);
    sesionCorreo.setDebug(true);

    try {
        conexionCorreo = sesionCorreo.getTransport("smtp");
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(NotificacionesManager.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        conexionCorreo.connect(usuarioAutenticacion, contrasenaAutenticacion);

Then I proceed to send the messages in the Queue, but I'm looking for a way for just set that connection once then start sending the mails in the queue when necessary.


Solution

  • The way that the Java EE designers intended you to do this is that you configure your javax.mail.Session object in your server. This is described in the Tomcat 7 JavaMail Sessions documentation.

    Your managed beans should then be able to access the session via @Resource:

    class MyManagedBean {
    
        @Resource(name="mail/Session") // this name is defined by your configuration
        private Session mailSession;
    
    
        public void someBusinessMethod() {
             ...
             Message message = new MimeMessage(mailSession);
             // compose message
             ...
             Transport.send(message);
        }
    
    }
    

    If you need to do this from a non-managed bean then you grab your Session instance using JNDI. This is described in the documentation linked above.