背景
按照之前写的文章 SpringBoot 中实现邮件发送功能 ,实现邮件发送功能后,在本地开发环境测试,邮件能够正常发送。但部署到阿里云 ECS 服务器以后,一直没有收到邮件。

一开始怀疑是条件判断有问题,后来添加 log 后发现,条件状态判断正常。再查看打印的相关 log,发现是在邮件发送时出现了异常。

问题报错
使用 SpringBoot 的邮件发送组件功能,发送邮件时,本地能够发送成功,但部署到阿里云 ECS 服务器后,却发送失败,部分关键 log 信息如下,

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.163.com, 25; timeout -1;
  nested exception is:
        java.net.ConnectException: 连接超时 (Connection timed out). Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.163.com, 25; timeout -1;
  nested exception is:
        java.net.ConnectException: 连接超时 (Connection timed out)
        at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:447)
        at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:322)
        at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:311)
1
2
3
4
5
6
7
8
问题解决
从现有情况看,跟程序运行环境有关。查看相关资料,发现在阿里云 ECS 服务器上,默认禁用了 25 端口,所以在通过 25 端口去连接邮件服务器时,无法连上,就报超时了。

官方建议使用 465 端口,而 456 端口是 SSL 协议的,所以不仅要换端口,还需要进行 SSL 协议替换。下面是在 application.properties 进行的邮件发送相关配置,

# JavaMailSender Config
spring.mail.host=smtp.163.com
spring.mail.username=xxx@163.com #你的163邮箱地址
spring.mail.password=xxx #你的163邮箱授权密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

# SSL Config
spring.mail.port=465
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
经过上面这样配置后,在阿里 ECS 上就能够正常发送邮件了。

服务器端口协议
163 邮箱相关服务器信息如下,

服务器名称    服务器地址    SSL 协议端口    非 SSL 协议端口
SMTP    smtp.163.com    465/994    25
欢迎关注我的公众号,一起进步!
————————————————
版权声明:本文为CSDN博主「ToSimpleL」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_38575051/article/details/93591123

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐