今天項目中有需要用到java mail發送郵件的功能,在網上找到相關代碼,代碼如下:
import java.io.IOException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) throws IOException, Exception {
String host = "smtp.163.com"; //發件人使用發郵件的電子信箱服務器
String from = "發件人的信箱"; //發郵件的出發地(發件人的信箱)
String to = "收件人信箱"; //發郵件的目的地(收件人信箱)
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", 25);
// Get session
props.put("mail.smtp.auth", "true"); //這樣才能通過驗證
MyAuthenticator myauth = new MyAuthenticator(from, "發件人的信箱密碼");
Session session = Session.getDefaultInstance(props, myauth);
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// Set the to address
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set the subject
message.setSubject("測試程序!");
// Set the content
message.setText("這是用java寫的發送電子郵件的測試程序!");
message.saveChanges();
Transport.send(message);
}
}
class MyAuthenticator extends javax.mail.Authenticator {
private String strUser;
private String strPwd;
public MyAuthenticator(String user, String password) {
this.strUser = user; this.strPwd = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(strUser, strPwd);
}
}
以上導入兩個jar包是activation-1.1.1.jar、javax.mail-1.5.4.jar
然後測試結果,總出現下面的錯誤:
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms:
LOGIN PLAIN DIGEST-MD5 NTLM DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN failed Exception in thread "main" javax.mail.AuthenticationFailedException: 535 Error: authentication failed
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826) at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685) at javax.mail.Service.connect(Service.java:317) at javax.mail.Service.connect(Service.java:176) at javax.mail.Service.connect(Service.java:125) at javax.mail.Transport.send0(Transport.java:194) at javax.mail.Transport.send(Transport.java:124) at com.eversec.smart.common.utils.SendMail.main(SendMail.java:131)
後來找到問題了,發現有兩個地方非常關鍵:
1、發件人郵箱一定要設置開啟“POP3/SMTP/IMAP”,其中必須要設置“客戶端授權密碼”,否則出錯;
2、發件人郵箱的密碼很關鍵,就是這一句MyAuthenticator myauth = new MyAuthenticator(from, "發件人的信箱密碼"); 此密碼必須是上面設置的客戶端授權密碼,否則就要出現上面的錯誤。