javamail郵件發送
阿新 • • 發佈:2018-12-14
ner 登錄 use pass trac cnblogs highlight ide one
按這條博客寫的方法https://www.cnblogs.com/xdp-gacl/p/4216311.html
日誌信息:
DEBUG SMTP: AUTH LOGIN command trace suppressed DEBUG SMTP: AUTH LOGIN succeeded DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle] DEBUG SMTP: need username and password for authentication DEBUG SMTP: protocolConnect returningfalse, host=smtp.sina.com, user=fyf, password=<null> javax.mail.AuthenticationFailedException: failed to connect, no password specified?
顯示登錄成功但是發送需要認證(need username and password for authentication)
所以session獲取方法需要修改,添加認證信息
Session session = Session.getInstance(prop);
改為
Session session = Session.getDefaultInstance(prop,new SimpleAuthenticator(USERNAME,PASSWORD));
其中SimpleAuthenticator類需要繼承javax.mail.Authenticator;
因為javax.mail.Authenticator;並沒有實現getPasswordAuthentication()方法,根據Authenticator中對該方法的描述
/** * Called when password authentication is needed. Subclasses should * override the default implementation, which returns null. <p> * * Note that if this method uses a dialog to prompt the user for this * information, the dialog needs to block until the user supplies the * information. This method can not simply return after showing the * dialog. * @return The PasswordAuthentication collected from the * user, or null if none is provided. */ protected PasswordAuthentication getPasswordAuthentication() { return null; }
當需要密碼認證是會被調用,子類必須實現該方法,並返回PasswordAuthentication,重寫代碼如下
代碼如下
package com.taotao.common.utils; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class SimpleAuthenticator extends Authenticator { private String username; private String password; public SimpleAuthenticator(String username, String password) { super(); this.username = username; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { // TODO Auto-generated method stub return new PasswordAuthentication(username, password); } }
再次運行發送成功
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2 DEBUG SMTP: Using mechanism LOGIN DEBUG SMTP: AUTH LOGIN command trace suppressed DEBUG SMTP: AUTH LOGIN succeeded DEBUG SMTP: use8bit false MAIL FROM:<[email protected]> 250 ok RCPT TO:<[email protected]> 250 ok DEBUG SMTP: Verified Addresses DEBUG SMTP: [email protected] DATA 354 End data with <CR><LF>.<CR><LF> Date: Fri, 14 Dec 2018 20:26:37 +0800 (CST) From: [email protected] To: [email protected]
javamail郵件發送