开始前准备
第一步:pom文件引入
<!-- 电子邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
第二部:application.properties配置
#这里使用qq信箱为例子
# 注意这里不是邮箱密码,而是SMTP授权密码
spring.mail.host = smtp.qq.com
spring.mail.username = 自己的信箱
spring.mail.password = 授权码
spring.mail.properties.mail.smtp.auth=true
#公司企业邮箱改为false
spring.mail.properties.mail.smtp.starttls.enable=true
#公司企业邮箱改为false
spring.mail.properties.mail.smtp.starttls.required=true
# ssl 配置 (非ssl发送一般是25端口,linux服务器一般都是禁用的,所以要切换465)
spring.mail.port=465
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.imap.ssl.socketFactory.fallback=false
spring.mail.properties.mail.smtp.ssl.socketFactory.class=com.fintech.modules.base.util.mail.MailSSLSocketFactory
第三部:执行测试代码
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private MailProperties mailProperties;
SimpleMailMessage message = new SimpleMailMessage();
// 发件人邮箱
message.setFrom(this.mailProperties.getUsername());
// 收信人邮箱
message.setTo(client.getEmail());
// 邮件主题
message.setSubject("简单邮件测试");
// 邮件内容
message.setText(textContent);
javaMailSender.send(message);
System.out.println("success");
完成!
注意报错问题:
springboot Couldn't connect to host, port: smtp.qq.com, 25; timeout -1; nested except
报错原因:非ssl发送一般是25端口,linux服务器一般都是禁用的,所以要切换465,另外需要配置# ssl 配置 为true
配置如下:
# ssl 配置 (非ssl发送一般是25端口,linux服务器一般都是禁用的,所以要切换465)
spring.mail.port=465
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.imap.ssl.socketFactory.fallback=false
spring.mail.properties.mail.smtp.ssl.socketFactory.class=com.fintech.modules.base.util.mail.MailSSLSocketFactory
打赏下了