将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: [email protected]
# 授权码
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
标签:qq,部署,javaMailSenderImpl,smtp,发送,mailProperties,properties,邮件
From: https://www.cnblogs.com/starychen/p/18129827