使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM