在使用javamail.jar发送邮件,无意中考虑多个帐号同时向某一个邮箱发送邮件,当使用Session.getDefaultInstance(pro,ma),第一次发送邮件总能成功,后面发送邮件就不能成功了,报第二个发送邮件地址和Authenticator中的设置不匹配。查看源码,
public static synchronized Session getDefaultInstance(Properties paramProperties, Authenticator paramAuthenticator)
/* */ {
/* 298 */ if (defaultSession == null) {
/* 299 */ defaultSession = new Session(paramProperties, paramAuthenticator);
/* */ }
/* 302 */ else if (defaultSession.authenticator != paramAuthenticator)
/* */ {
/* 304 */ if ((defaultSession.authenticator == null) || (paramAuthenticator == null) || (defaultSession.authenticator.getClass().getClassLoader() != paramAuthenticator.getClass().getClassLoader()))
/* */ {
/* 311 */ throw new SecurityException("Access to default session denied");
/* */ }
/* */ }
/* 314 */ return defaultSession;
/* */ }
这里他使用了一个单例类,程序中只有一个Authenticator验证对象,所有使用第二个帐号发送邮件的时候,Authenticator还是保存的第一个帐号的信息,就会抛出异常。
所以如果使用多个帐号发送邮件的话,请使用Session getInstance(Properties paramProperties, Authenticator paramAuthenticator);源码如下:
public static Session getInstance(Properties paramProperties, Authenticator paramAuthenticator)
/* */ {
/* 232 */ return new Session(paramProperties, paramAuthenticator);
/* */ }
会去重新实例一次,保证了每一个会话的独立性。
这样就能使用多个帐号发送邮件了,在发送邮件的时候,最好采用线程,有些邮箱的验证连接还是需要一点时间的。
多帐号使用javamail发送邮件问题
猜你喜欢
转载自buerkai.iteye.com/blog/1667435
今日推荐
周排行