第三讲:JavaMail中Session类
mail.jar架包中的javax.mail.Session类用于定义整个JavaMail应用程序所需要的环境信息,以及收集客户端与邮件服务器建立网络连接的会话信息。例如邮件服务器的主机名、端口号、采用的邮件发送和接收协议等。同时Session对象根据这些信息构建用于邮件收发的Transport和Store对象,以及为客户端创建Message对象时提供信息支持。
一、Session常用函数 下面的表格中列出了Session常用的方法。包括获取Transport、Stored对象等
public static getInstance(java.util.Properties) public static getInstance(java.util.Properties ,Authenticator) | 获取Session对象的方法,由于Session的构造方法是私有的因此只能通过静态方法获取 |
public static getDefalutInstance(java.util.Properties) public static getDefaultInstance(Properties ,Authenticator) | |
getTransport() getTransport(java.lang.String protocol) | 默认根据mail.transport.protocol属性中的协议创建。 返回实现了指定的具体邮件发送协议的Transport对象。Transport是抽象类,两个方法返回的都是实现某种协议的Transport的子类 |
getStore() getStore(java.lang.String protocol) | 默认根据mail.store.protocol属性中的协议创建接收邮件对象。 返回实现了指定具体邮件接收协议的Store对象。Store也是抽象类,两个方法返回的都是实现某种协议的Store的子类 |
setDebug(boolean debug) | 当设置为true时,JavaMail AP就会将其运行过程和邮件服务器的交互命令信息输出到运行窗口中,用于JavaMail的调试有用。 |
PS:getInstance和getDefaultInstance方法的区别在于:getDefaultInstance方法返回一个Session对象后,将这个Session对象安装为默认的Session对象,以后每次调用getDefaultInstance方法都将返回这个默认Session对象;而getInstance方法则是每次调用都返回一个新的Session对象。
1.1 参数Properties 对Properties类中可以通过setProperty(String key, String value)方法进行设置,其取值包括 :
1.2 参数Authenticator 在JavaMail中除了可以通过Transport.connect(host, user, passqord)方法在连接SMTP服务器是直接传递用户认证信息还可以借助Authenticator类来 获取用户认证信息 当使用Session的getInstance(properties, Authenticator)来创建Session对象时,会将Authenticator对象注册到该Session。以后这个Session对象的JavaMail客户端程序要向邮件服务器提交认证信息时,将调用该Session对象中注册的Authenticator对象,从中获取用户认证信息后传递给邮件服务器。
Authenticator类最常用的一个方法是: protected PasswordAuthentication getPasswordAuthentication(); Authenticator类是抽象类,传递给getInstance方法的Authenticator对象只能是其子类的实例对象。Authenticator对定义的该方法的返回值为null,因此其子类必 须覆盖该方法,由邮件开发人来实现。
PasswordAuthentication类中的方法有:
public PasswordAuthentication(String userName, String password) |
public String getUserName(); |
public String getPassword(); |