Javamail接收用pop3协议接收邮件的时候,我们可以通过创建一个Authenication类来保存用户验证信息
public class MyAuthenticator extends Authenticator {
private String strUser;
private String strPswd;
/**
* Initial the authentication parameters.
*
* @param username
* @param password
*/
public MyAuthenticator(String username, String password) {
this.strUser = username;
this.strPswd = password;
}
/**
* @return
*/
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(strUser, strPswd);
}
}
然后再session当中使用这个类的实例
Properties props = null;
Session session = null;
props = System.getProperties();
props.put("mail.pop3.host", host);
props.put("mail.pop3.auth", "true");
props.put("mail.pop3.port", port);
Authenticator auth = new MyAuthenticator(userName, password);
session = Session.getDefaultInstance(props, auth);
Store store = session.getStore("pop3");
store.connect();
...
这样我们就可以通过一个MyAuthenticator来保存用户的验证信息了。
当我们使用单个线程运行的时候,以上的代码或许会运行正确,但是在多线程的环境下,此段代码有可能引发AuthenticatioinFailedException
原因在于session和props不是一个独立的实例,在多线程的时候会互相影响,特别在读取不同的POP3服务器的时候
这个时候我们需要对第2段代码进行一些改动
Properties props = null;
Session session = null;
// props = System.getProperties();
props = new Properties();
props.put("mail.pop3.host", host);
props.put("mail.pop3.auth", "true");
props.put("mail.pop3.port", port);
Authenticator auth = new MyAuthenticator(userName, password);
// session = Session.getDefaultInstance(props, auth);
session = Session.getInstance(props, auth);
Store store = session.getStore("pop3");
store.connect();
...
new Properties()以及session.getInstance(props, auth)就会确保每一个线程之间的实例都是独立的,在多线程运行环境下保证资源不冲突,避免了AutherticationFailedException的发生。
(欢迎指正和补充)