title: What is the use of javax.mail.Session?
body: <p>I was fixing a class responsible for sending emails. It looked like this (simplified):</p>
  
  <pre><code>/* ... */
  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) { /* ... */ }
  /* ... */
  </code></pre>
  
  <p>During my work I set <code>session</code> to <code>null</code> and to my utter surprise the class still worked fine. It doesn't matter if I pass <code>null</code> to <code>MimeMessage</code> constructor. It doesn't throw an exception or anything. Moreover, the <code>Transport.send()</code> method includes the following lines:</p>
  
  <p><code>240    Session s = (msg.session != null) ? msg.session :
   241    Session.getDefaultInstance(System.getProperties(), null);</code></p>
  
  <p>So if the session is <code>null</code> it just creates a new one using system properties. What is then the purpose of creating a <code>Session</code> object at all? Why doesn't <code>MimeMessage</code> have a default constructor if it doesn't matter what you pass in there?</p>
  
  <p>I viewed a number of examples of using javax.mail, such as: <a href="https://developers.google.com/appengine/docs/java/mail/usingjavamail" rel="noreferrer">example from Google</a> and 
  <a href="http://www.tutorialspoint.com/java/java_sending_email.htm" rel="noreferrer">example from tutorialspoint</a> and they both create a <code>Session</code> object which seems pretty useless. Why would anyone do that?</p>