1.引入jar包依赖
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
2.Java代码
// 邮箱账号
String emailAcct = "XXX@163.com";
// 密码\安全码
String emailPwd = "XXX";
// 用于连接邮件服务器的参数配置
Properties props = new Properties();
// 协议
props.setProperty("mail.transport.protocol", "smtp");
// 服务器
props.setProperty("mail.smtp.host", "fastsmtphz.qiye.163.com");
// 端口
props.setProperty("mail.smtp.port", "465");
// 使用smtp身份验证
props.setProperty("mail.smtp.auth", "true");
// 开启安全协议
props.setProperty("mail.smtp.ssl.enable", "true");
// 信任所有主机
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.setProperty("mail.smtp.ssl.socketFactory", sf);
// 创建认证对象
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailAcct, emailPwd);
}
};
// 根据参数配置,创建会话对象
Session session = Session.getInstance(props, authenticator);
// 开启debug模式打印日志
//session.setDebug(true);
// 1. 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(emailAcct));
// 3. To: 收件人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email.getRecipient()));
// 4. Subject: 邮件主题
message.setSubject(email.getSubject(), "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
message.setContent(email.getContent(), "text/html;charset=UTF-8");
// 6. 设置显示的发件时间
message.setSentDate(new Date());
// 7. 保存前面的设置
message.saveChanges();
// 8. 发送
Transport.send(message);