Springboot发送邮件

1. pom包配置


   org.springframework.boot
    spring-boot-starter-mail

2. yml文件配置

spring.mail.properties.mail.smtp.auth: true
spring.mail.properties.mail.smtp.starttls.enable: true
spring.mail.properties.mail.smtp.starttls.required: true
spring.mail.properties.mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
spring.mail.properties.content.user.update.pwd.subject: 您正在修改账号密码,请打开邮件获取验证码
spring.mail.properties.content.user.update.pwd.text: 您正在修改账号密码,验证码是${captcha}。如有疑问请联系管理员

spring.mail.properties.content.user.register.subject: 您正在注册,请打开邮件获取验证码
spring.mail.properties.content.user.register.text: 您正在注册,验证码是${captcha}。如有疑问请联系管理员

spring.mail.properties.content.email.binding.subject: 您正在绑定邮箱,请打开邮件获取验证码
spring.mail.properties.content.email.binding.text: 您正在绑定邮箱,验证码是${captcha}。如有疑问请联系管理员

3. 代码实现邮件发送

@Resource
private MailProperties mailProperties;
@Resource
JavaMailSender javaMailSender;
@Resource
private HttpServletRequest request;
@Resource
private HttpServletResponse response;


   /**
     * 发生邮件
     * @param email 邮箱
     * @param contentKey 模板配置文件中配置
     * @param paras 参数
     */
    private void sendEmail(String email, String contentKey, Map paras) {
        SimpleMailMessage message = new SimpleMailMessage();

        message.setTo(email);
        message.setFrom(mailProperties.getUsername());
        message.setSubject(mailProperties.getProperties().get(contentKey + ".subject"));

        String text = mailProperties.getProperties().get(contentKey + ".text");
        if (text != null) {
            for (String key : paras.keySet()) {
                text = text.replace(String.format("${%s}", key), paras.get(key));
            }
            message.setText(text);
        }
        try {
            javaMailSender.send(message);
        } catch (MailException e) {
            throw new AdminException(e, ErrorCode.ADMIN_CREATE_MAIL_SEND_FAIL);
        }
    }

你可能感兴趣的:(Springboot发送邮件)