java(JDK1.8)通过smtp协议发邮件问题,报如下错:
解决方案(1和2 缺一不可,必须都要设置,反正我当时是这样的情况):
1、javax.mail包 由1.4升级到1.4.7
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
2、添加代码(手动设置TLS版本,与邮箱服务器TLS版本保持一致):
properties.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
java 用smtp协议发邮件的完整代码如下:
package com.example.demo;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws Exception {
testAT();
}
static void testAT() throws UnsupportedEncodingException, MessagingException {
try{
/**
* 1.配置发件人邮箱信息以及创建一个Java 配置类存放SMTP服务器地址等参数。
*/
// 发件人邮箱
String sendEmailAccount = "xxx";
// 发件人密码
String sendEmailPassword = "xxx";
// 发件人邮箱的 SMTP 服务器地址, 此处为Outlook邮箱的SMTP服务器
String sendEmailSMTPHost = "xxx";
// 收件人邮箱
String receiveMailAccount = "xxx";
// 使用Java配置类进行配置
Properties props = new Properties();
// 使用的协议(JavaMail规范要求)
props.setProperty("mail.transport.protocol", "smtp");
// 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.host", sendEmailSMTPHost);
// 需要请求认证
props.setProperty("mail.smtp.auth", "true");
// 默认端口号设置为587,也可以设置为465,具体取决于SMTP服务器要求的端口号
final String smtpPort = "587";
props.setProperty("mail.smtp.port",smtpPort );
props.setProperty("mail.smtp.starttls.enable", "true");
//props.setProperty("mail.smtp.ssl.trust", "*" );
props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
/**
* 2.创建一个同邮件服务器交互的session
*/
Session session = Session.getInstance(props, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sendEmailAccount, sendEmailPassword);
}
});
session.setDebug(true); //打印执行的command,方便开发调试
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(sendEmailAccount, "ExampleFrom", "UTF-8"));
// 3. To: 收件人
message.setRecipient(MimeMessage.RecipientType.TO,
new InternetAddress(receiveMailAccount, "ExampleUser", "UTF-8"));
// 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题)
message.setSubject("test", "UTF-8");
// 5. Content: 邮件正文
message.setContent("<h3>This is a test email.</h3>", "text/html;charset=UTF-8");
// 6. 设置邮件发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
/**
* 3.创建一封格式化的邮件
*/
// 1. 根据 Session 获取邮件传输对象
Transport transport = session.getTransport();
// 2. 使用 邮箱账号 和 密码 连接邮件服务器
transport.connect(sendEmailAccount, sendEmailPassword);
// 3. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人,
transport.sendMessage(message, message.getAllRecipients());
// 4. 关闭连接
transport.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}