SpringBoot 发送邮件默认使用JavaMailSenderImpl实例进行操作
application.yml配置:
spring:
mail:
host: smtp.exmail.qq.com
port: 465
username: xxxx
password: xxx
default-encoding: UTF-8
如果邮件服务器配置了SSL,端口465,则需要自定义配置JavaMailSenderImpl实例
@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();
//如果连接25端口以外的端口就必须有这个参数设置,且配置文件中的配置需要手动导入到JavaMailSenderImpl才能在其中使用
properties.put("mail.smtp.ssl.enable", true);
javaMailSenderImpl.setJavaMailProperties(properties);
}
return javaMailSenderImpl;
}