Storing the mail session (javax.mail.Session) in a singleton is a good practice? Me and my team decided to keep a single mail session in a static variable inside a Singleton class.
So, in the private constructor we do this:
try {
Properties props = new Properties();
props.put("mail.transport.protocol", config.getMailTransportProtocol());
props.put("mail.smtp.starttls.enable", config.getMailStarttlsEnable());
props.put("mail.smtp.host", config.getMailHost());
props.put("mail.smtp.auth", config.getMailAuth());
props.put("mail.smtp.user", config.getMailFrom());
props.put("mail.debug", config.getMailDebug());
props.put("mail.smtp.port", config.getMailPort());
props.put("mail.smtp.socketFactory.port", config.getMailPort());
props.put("mail.smtp.socketFactory.class", config.getMailSocketFactoryClass());
props.put("mail.smtp.socketFactory.fallback", config.getMailSocketFactoryFallback());
props.put("mail.pop3.host", config.getMailPop3Host());
props.put("mail.store.protocol", config.getMailStoreProtocol());
SimpleAuth auth = new SimpleAuth(config.getMailUser(), config.getMailPass());
MailSession.session = Session.getDefaultInstance(props, auth);
session.setDebug(config.getMailDebug());
} catch (Throwable ex) {
System.err.println("Initial MailSession creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
But I’m worried if is best keeping it like this or opening and closing a session for each e-mail.
First, you’ll want to read this JavaMail FAQ entry on common mistakes.
And if you read the javadocs for the Session.getDefaultInstance method, you’ll see that JavaMail already maintains a singleton Session for you. If you never change the configuration of the Session, this might work for you, although generally I recommend against it.