SpringBoot发送邮件Mail

今天在idea中使用springboot来实现发送Mail功能,编码很顺利,但是在测试发送邮件时报错,

nested exception is:
	java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.qq.com, 25; timeout -1;
  nested exception is:
	java.net.ConnectException: Connection refused: connect; message exceptions (1) are:
Failed message 1: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.qq.com, 25; timeout -1;
  nested exception is:
	java.net.ConnectException: Connection refused: connect] with root cause
 
java.net.ConnectException: Connection refused: connect

查找了一些资料,原来如果自己主机上同时支持ipv4和ipv6,java虚拟机会默认选择ipv6,这就找不到host了,因为我们电脑现在普遍ipv4,所以就会报连接出错:java.net.ConnectException: Connection refused: connect

解决办法参考我的另一篇csdn上的blog: Spring Mail用QQ邮箱测试发送邮件失败【连接超时】

好了,下面让我们来看一下如何使用SpringBoot来集成Mail,实现邮件发送功能。

1、引入Pom文件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2、配置application.properties或者application.yml文件,我以.properties格式为例

# 设置邮箱主机
spring.mail.host=smtp.qq.com
# 发送方的邮箱
[email protected]
# 设置密码,该处的密码是QQ邮箱开启SMTP的授权码而非QQ密码
spring.mail.password=xxxxx
# 设置是否需要认证,如果为true,那么用户名和密码就必须的,
# 如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。
spring.mail.properties.mail.smtp.auth=true
# STARTTLS 是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8

3、引入测试代码

@RestController
public class MailController {

    @Autowired
    private JavaMailSender mailSender;

    @GetMapping("/sendMail")
    public String sendMail() {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("[email protected]");
        message.setTo("[email protected]");
        message.setSubject("主题:简单邮件");
        message.setText("测试邮件内容ffff");

        mailSender.send(message);
        return "SUCCESS";
    }
}

需要注意的是application配置文件中的spring.mail.password=并不是指你的邮箱密码,而是qq邮箱的授权码,这个授权码需要你在qq邮箱里自己开启smtp获取的,具体方法参考:QQ邮箱开启SMTP方法如何授权

这样就完成了,感兴趣的小伙伴赶快试一下吧!

参考资料:Spring 发送邮件 HTML邮件

猜你喜欢

转载自blog.csdn.net/m0_37732829/article/details/90637922