Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of javax.mail.Session?

I was fixing a class responsible for sending emails. It looked like this (simplified):

/* ... */
Properties props = System.getProperties();
props.put("mail.smtp.host", A_VALID_IP_OF_MAIL_SERVER);
Session session = Session.getDefaultInstance(props, null);  

try {
    Message msg = new MimeMessage(session);
    /* msg.setFrom(); msg.addRecipient(); etc. */
    Transport.send(msg);
    System.out.println("Sent!");
}
catch (Exception e) { /* ... */ }
/* ... */

During my work I set session to null and to my utter surprise the class still worked fine. It doesn't matter if I pass null to MimeMessage constructor. It doesn't throw an exception or anything. Moreover, the Transport.send() method includes the following lines:

240 Session s = (msg.session != null) ? msg.session : 241 Session.getDefaultInstance(System.getProperties(), null);

So if the session is null it just creates a new one using system properties. What is then the purpose of creating a Session object at all? Why doesn't MimeMessage have a default constructor if it doesn't matter what you pass in there?

I viewed a number of examples of using javax.mail, such as: example from Google and example from tutorialspoint and they both create a Session object which seems pretty useless. Why would anyone do that?

like image 319
Bartek Maraszek Avatar asked Mar 26 '14 10:03

Bartek Maraszek


1 Answers

What is then the purpose of creating a Session object at all?

The session is the context of how you are going to interact with the mail host. This includes but not limited to debugging output from the mail host, timeouts, and authentication mechanisms. If you want to interact with the same mail host in different ways then the session is the object that holds this information.

If a single JVM needs to connect to multiple mail servers you need two different sessions. This is explained in detail in the JavaMail FAQ:

If some other code in the same JVM (e.g., in the same app server) has already created the default Session with their properties, you may end up using their Session and your properties will be ignored. This often explains why your property settings seem to be ignored. Always use Session.getInstance to avoid this problem.

Most JavaMail examples fail the common mistakes test. Try to reference the JavaMail API sample programs Session.getDefaultInstance is rarely the right choice for any code. Most code should use Session.getInstance. Including a default constructor for MimeMessage would just encourage wrong behavior.

like image 119
jmehrens Avatar answered Nov 15 '22 16:11

jmehrens