java mail smtps,SpringBoot整合JavaMail,通过smtps发送邮件

pom文件加入依赖

org.springframework.boot

spring-boot-starter-mail

yml配置

spring:

mail:

port: 465

host: 邮箱服务器地址

username: 邮箱用户

password: 密码

default-encoding: UTF-8

protocol: smtps

properties:

mail:

smtp:

ssl:

enable: true

socketFactory:

port: 465

class: javax.net.ssl.SSLSocketFactory

auth: true

starttls:

enable: true

required: true

MailService注入JavaMailSenderImpl

import org.springframework.mail.javamail.JavaMailSenderImpl;

import org.springframework.mail.javamail.MimeMessageHelper;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import javax.mail.MessagingException;

import javax.mail.internet.MimeMessage;

import java.io.File;

public class MailService {

private JavaMailSenderImpl mailSender;

public void sendMail() {

// 发送邮件是耗时任务,需要另起线程,不影响主线程。此处可使用线程池处理

new Thread(() -> {

MimeMessage msg = mailSender.createMimeMessage();

MimeMessageHelper msgHelper = null;

try {

msgHelper = new MimeMessageHelper(msg, true);

msgHelper.setFrom("[email protected]");

msgHelper.setTo("[email protected]");

msgHelper.setSubject("Test!");

msgHelper.setText("测试!");

msgHelper.addAttachment("PI_sf2_data.zip", new File("C:\\Users\\42193\\Desktop\\PI_sf2_data.zip"));

} catch (MessagingException e) {

e.printStackTrace();

}

mailSender.send(msg);

}).start();

}

}

运行程序,报错:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:

sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

原因:找不到安全证书

解决方案:手动导入证书进行认证

下载保存证书

下载证书,浏览器访问邮箱服务器,点击锁按钮,点击【证书】

java mail smtps,SpringBoot整合JavaMail,通过smtps发送邮件_第1张图片

点击【复制到文件】->【下一步】->选择Base64,【下一步】

java mail smtps,SpringBoot整合JavaMail,通过smtps发送邮件_第2张图片

java mail smtps,SpringBoot整合JavaMail,通过smtps发送邮件_第3张图片

java mail smtps,SpringBoot整合JavaMail,通过smtps发送邮件_第4张图片

保存证书

java mail smtps,SpringBoot整合JavaMail,通过smtps发送邮件_第5张图片

java mail smtps,SpringBoot整合JavaMail,通过smtps发送邮件_第6张图片

这里我保存到桌面

## 导入证书

切换到jre的\lib\security目录下

C:\Users\42193>d:

D:\>cd devinstall\Java\jdk1.8.0_152\jre\lib

导入证书,秘钥库口令:changeit

D:\devinstall\Java\jdk1.8.0_152\jre\lib\security>keytool -import -alias test -keystore cacerts -file C:\Users\42193\Desktop\test.cer

输入密钥库口令:

alias:取别名

keystore:证书保存的文件名

将看到如下内容

java mail smtps,SpringBoot整合JavaMail,通过smtps发送邮件_第7张图片

输入"Y",添加成功

是否信任此证书? [否]: y

证书已添加到密钥库中

可查看证书

43c9a8ef69de25b4eb234371db078f51.png

至此,证书添加成功,重新运行程序即可!

你可能感兴趣的:(java,mail,smtps)