使用javax.mail,通过SMTP来发送邮件,代码如下:
@Override
public void validateMail(String to) throws Exception{
//创建Properties,并设置主机和认证
Properties props = new Properties();
props.setProperty("mail.host", "smtp.qq.com");
props.setProperty("mail.smtp.auth", "true");
//开启SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
//创建Authenticator内部类,重写getPasswordAuthentication()方法
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("userName", "password");
}
};
//获取Session
Session session = Session.getInstance(props, auth);
//创建MimeMessage
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("---------@qq.com"));
msg.setRecipients(RecipientType.TO, to);
msg.setSubject("来自的一封邮件");
msg.setContent("这是一封垃圾邮件", "text/html;charset=utf-8");
//发送
Transport.send(msg);
}
测试时抛出异常:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465;
解决办法:
我的环境是eclipse,过去在myeclipse中这段代码是没有错的。找出以前写的项目,测试了下,依旧是能正确运行的。
在网上寻找了一些相关信息:http://blog.csdn.net/levy_cui/article/details/51143104
这篇博客的评论里说是jdk1.8的security级别问题导致的,按照他的说法实验了一下,问题成功解决。
附上下载地址:百度网盘