SpringBoot 发送邮件开启SSL

发布时间:2023-04-02 19:00

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;
    }

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号