出现的错误如下:
org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.qq.com:465
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1469)
at org.apache.commons.mail.Email.send(Email.java:1496)
at emailtest.Test.main(Test.java:21)
Caused by: javax.mail.AuthenticationFailedException: 535 Error: ÇëʹÓÃÊÚȨÂëµÇ¼¡£ÏêÇéÇë¿´: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:950)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:861)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:766)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1459)
... 2 more
代码:
public class Test {
public static void main(String[] args) {
Email email = new SimpleEmail();
email.setHostName("smtp.qq.com");// 发送服务器的名字
email.setAuthenticator(new DefaultAuthenticator("123456789@qq.com", "zzz"));//邮箱名和密码
email.setSSLCheckServerIdentity(true);
email.setSSLOnConnect(true);
email.setSmtpPort(465);
try {
email.setFrom("123456789@qq.com");
email.setSubject("测试");// 发送主题
email.setMsg("邮件测试内容!");// 发送内容
email.addTo("123456789@qq.com");// 接受邮件账户
email.send();// 发送
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 发送邮箱
}
}
使用的jar包如下:
使用如上代码,首先确保邮箱已经开启了 POP3、SMTP等服务。
开启之后,一定要生成授权码,上面的邮箱名和密码
email.setAuthenticator(new DefaultAuthenticator("123456789@qq.com", "zzz"));//邮箱名和密码
密码是授权码,而不是你的邮箱真正的密码。