javax.mail.Session有什么用?

我正在修一个负责发送电子邮件的班级.它看起来像这样(简化):
/* ... */
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) { /* ... */ }
/* ... */

在我的工作中,我将会话设置为null,令我惊讶的是,课程仍然很好.如果我将null传递给MimeMessage构造函数并不重要.它不会抛出异常或任何东西.此外,Transport.send()方法包括以下行:

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

因此,如果会话为null,则只使用系统属性创建一个新会话.那么创建一个Session对象的目的是什么呢?为什么MimeMessage没有认构造函数,如果你传递的内容无关紧要?

我查看了许多使用javax.mail的例子,例如:example from Google
example from tutorialspoint并且它们都创建了一个看起来很无用的Session对象.为什么有人这样做?

解决方法

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

会话是您与邮件主机进行交互的上下文.这包括但不限于调试来自邮件主机的输出,超时和身份验证机制.如果要以不同方式与同一邮件主机进行交互,则会话是保存此信息的对象.

如果单个JVM需要连接到多个邮件服务器,则需要两个不同的会话.这在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.

大多数JavaMail示例都未通过common mistakes测试.尝试引用JavaMail API sample programs Session.getDefaultInstance很少是任何代码的正确选择.大多数代码都应该使用Session.getInstance.包含MimeMessage的认构造函数只会鼓励错误的行为.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...