Javamail 的AuthenticationFailedException异常

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的发生。

 

(欢迎指正和补充)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值