您的位置:首页 > 编程语言 > Java开发

java 通过qq邮箱发邮件

2016-12-16 22:12 351 查看
直接上代码

package com.lb;

import org.junit.Test;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
* Created by CodingQiang on 2016/12/16.
*/
public class EmailTest {

@Test
public void emailTest() throws Exception
{
// 创建Properties 类用于记录邮箱的一些属性
final Properties props = new Properties();
// 表示SMTP发送邮件,必须进行身份验证
props.put("mail.smtp.auth", "true");
//此处填写SMTP服务器
props.put("mail.smtp.host", "smtp.qq.com");
//端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587
props.put("mail.smtp.port", "587");
// 此处填写你的账号
props.put("mail.user", "*****@qq.com");
// 此处的密码就是前面说的16位STMP口令 授权码
props.put("mail.password", "**********");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//        props.put("mail.smtp.socketFactory.fallback", "false");

// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);

// 设置收件人的邮箱
InternetAddress to = new InternetAddress("*******@163.com");
message.setRecipient(MimeMessage.RecipientType.TO, to);

// 设置邮件标题
message.setSubject("测试邮件");

// 设置邮件的内容体
message.setContent("这是一封测试邮件", "text/html;charset=UTF-8");

// 最后当然就是发送邮件啦
Transport.send(message);
}
}


注:当用jdk的是1.8的要注意了,可能会报下面这个错误:

Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465;

nested exception is: javax.NET.ssl.SSLHandshakeException: Received fatal alert: handshake_failure. Failed messages: javax.mail. MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465;

nested exception is: javax.Net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure


当时我就是报这个错,我调试了好久,才在网上找到答案:

这个问题是jdk导致的,jdk1.8里面有一个jce的包,安全性机制导致的访问https会报错,官网上有替代的jar包,如果替换掉就可以了。问题的解决方法还可以就是在整个项目中把你的jdk换成是1.7.

这两个jar包的下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

这样就好了!

代码亲测可以运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java qq邮箱 邮件