將spring boot3專案部署到阿里雲伺服器執行,傳送郵件時報錯 Could not connect to SMTP host: smtp.qq.com, port: 25, response: -1
原因
阿里雲伺服器出於安全策略的考慮,主動遮蔽了伺服器25埠,導致郵件服務無法正常使用。
解決辦法
重新編寫自定義JavaMailSenderImpl,並註冊為Bean,郵件的埠改為 465
@Bean
public JavaMailSenderImpl mailSender(MailProperties mailProperties) {
JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
javaMailSenderImpl.setHost(mailProperties.getHost());
javaMailSenderImpl.setUsername(mailProperties.getUsername());
javaMailSenderImpl.setPassword(mailProperties.getPassword());
javaMailSenderImpl.setDefaultEncoding(StandardCharsets.UTF_8.name());
javaMailSenderImpl.setPort(mailProperties.getPort());
if (mailProperties.getPort() == 465) {
Properties properties = new Properties();
properties.put("mail.smtp.ssl.enable", true);
javaMailSenderImpl.setJavaMailProperties(properties);
}
return javaMailSenderImpl;
}
上傳伺服器執行,出現如下錯誤
只需在@Configuration下新增 @Import(MailProperties.class) 把屬性匯入進來就行了
第二種方案(本人沒有測試,貌似原理差不多)
直接在 application.yml 中新增如下配置
spring:
# SpringMail傳送郵件相關配置
mail:
# 傳送郵件的賬號名
username: xxxxxxxxxxxx@qq.com
# 授權碼
password: xxxxxxxxxxxx
# smtp服務主機 qq郵箱的服務主機為smtp.qq.com
host: smtp.qq.com
# 服務協議
protocol: smtp
# 編碼集
default-encoding: UTF-8
# 服務埠
port: 465
properties:
mail:
smtp:
auth: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory //這裡可能有問題springboot3內建的是tomcat10,依賴包名應該是jakarta
fallback: false
starttls:
enable: true
required: true