今天项目中有需要用到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, "发件人的信箱密码"); 此密码必须是上面设置的客户端授权密码,否则就要出现上面的错误。
http://www.cnblogs.com/zhh-bky/articles/4725209.html