javax. mail. What’s the use of session?

I'm taking a class in charge of sending e - mail It looks 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) { /* ... */ }
/* ... */

In my work, I set the session to null. To my surprise, the course is still very good It doesn't matter if I pass null to the mimemessage constructor It doesn't throw exceptions or anything In addition, transport The send() method includes the following lines:

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

Therefore, if the session is null, only system properties are used to create a new session So what is the purpose of creating a session object? Why does mimemessage have no default constructor if what you pass doesn't matter?

I've looked at a lot of using javax Mail examples, such as example from Google and example from tutorial point, and they both create a seemingly useless session object Why would anyone do that?

Solution

A session is the context in which you interact with the mail host This includes but is not limited to debugging output from the mail host, timeout and authentication mechanisms If you want to interact with the same mail host in different ways, the session is the object to save this information

If a single JVM needs to connect to multiple mail servers, two different sessions are required This is explained in detail in the JavaMail FAQ:

Most of the JavaMail samples failed the common misses test Try to reference JavaMail API sample programs session Getdefaultinstance is rarely the right choice for any code Most code should use session getInstance. The default constructor containing mimemessage only encourages wrong behavior

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>