使用SpringBoot + JavaMailSender 发送邮件报错 Mail server connection failed;Could not connect to SMTP host

说明:

出于安全考虑,阿里云默认封禁 TCP 25 端口出方向的访问流量,无法在阿里云上的云服务器通过 TCP 25 端口连接外部地址。

【官方提示】:如果您需要使用阿里云上的云服务器对外部发送邮件,建议您使用阿里云邮产品或者使用第三方邮件服务商提供的 465 端口。记得添加安全组配置

如果你确实需要使用 25 端口,可在安全管控平台中提交25端口解封申请,地址:https://help.aliyun.com/knowledge_detail/56130.html

但修改为 465 端口后发送邮件会报错

报错信息如下:

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1. Failed messages: javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1

解决办法:

在 application.yml 中将邮件配置为 SSL 连接

spring:
  mail:
    host: smtp.qq.com
    username: 你的邮箱账号
    password: 你的邮箱授权码(QQ邮箱)
    port: 465
    protocol: smtp
    default-encoding: utf-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
          ssl:
            enable: true
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory

如果你使用的是 properties 文件,应该修改为:

# JavaMailSender 配置
spring.mail.host=smtp.qq.com
spring.mail.username=你的邮箱账号
spring.mail.password=你的邮箱授权码(QQ邮箱)
spring.mail.port=465
spring.mail.default-encoding=utf-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
# SSL 配置
spring.mail.protocol=smtp
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

推荐一个 yml、properties 文件在线转换的网站 https://toyaml.com/index.html

posted @ 2020-03-26 20:11  农夫三拳有点疼~  阅读(4860)  评论(0编辑  收藏  举报