What is the use of javax.mail.Session?

I fixed the class responsible for sending emails. It was like (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 complete surprise, the class still worked fine. It doesn't matter if I pass the null constructor to MimeMessage . This is not an exception or something else. In addition, 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 the system properties. What is the purpose of creating a session object? Why MimeMessage n't MimeMessage have a default constructor if it doesn't matter what you go through there?

I looked at some examples of using javax.mail, for example: an example from Google and an example from tutorialspoint , and both of them create a session object that seems pretty useless. Why would anyone do this?

+6
source share
1 answer

What is the purpose of creating a Session object in general?

A session is the context of how you intend to interact with the mail node. This includes, but is not limited to, debugging output from the mail host, timeouts, and authentication mechanisms. If you want to interact with the same mail node in different ways, then the session is an object that contains 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 any other code in the same JVM (for example, on the same application server) already created a default session with its own properties, you can end up using your own 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.

In most JavaMail examples, the common errors test fails. Try looking at the sample JavaMail API programs. Session.getDefaultInstance rarely the right choice for any code. In most cases, the code should be used by Session.getInstance . Enabling the default constructor for MimeMessage will simply contribute to misbehavior.

+10
source

All Articles