springboot邮件发送(QQ邮箱)

  1. yml配置文件
spring:
  mail:
    host: smtp.qq.com
    port: 587
    username: 发件人的QQ邮箱
    password: QQ邮箱里设置-》账户-》开启POP3/SMTP服务-》取得的码
    protocol: smtp
    default-encoding: UTF-8
    properties:
      mail.smtp.auth: true
      mail.smtp.starttls.enable: true
      mail.smtp.starttls.required: true
      mail.smtp.socketFactory.port: 465
      mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
      mail.smtp.socketFactory.fallback: false
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
    check-template-location: true
    suffix: .html
    encoding: UTF-8
    servlet:
      content-type: text/html
    mode: HTML
  1. 代码

1 导入jar包

    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

2 创建一个发送邮件的类,将以下两个注入,并写一个得到数据的函数

	@Resource
    private JavaMailSender mailSender;
    private final TemplateEngine templateEngine;

    // EmailBody 为携带的抬头和数据,template为在templates文件夹下展示给用户看的邮件的html页面,toEmail是收件人
    private MimeMessage getMimeMessage(final EmailBody body, final String template, final String toEmail
    ) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(emailFrom);
        mimeMessageHelper.setTo(toEmail);
        mimeMessageHelper.setSubject(body.getTitle());
        mimeMessageHelper.setText(templateEngine.process(template, body.getContext()), true);
        return mimeMessage;
    }

3 创建一个荷载数据的类,其中email.title为邮件的抬头,email.context为荷载,context.setVariable(“expire”, time);的expire为页面上要展示的文本的名字。

@AllArgsConstructor
@NoArgsConstructor
@Data
public class EmailBody {
    @JsonIgnore
    private static final String DEFAULT_TITLE = "密码重置";

    private String title;
    private Context context;

    public static EmailBody build(final int random, final Long time) {
        EmailBody email = new EmailBody();
        Context context = new Context();
        context.setVariable("random", random);
        context.setVariable("expire", time);
        email.title = DEFAULT_TITLE;
        email.context = context;
        return email;
    }
}

4 发送,可以用线程池发送

    public void notifyPasswordReset(final MimeMessage mimeMessage) throws MessagingException {
            mailSender.send(mimeMessage));
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

syf_wfl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值