@TedZhou
2020-08-28T10:38:10.000000Z
字数 2510
阅读 587
java spring mail thymeleaf
发送邮件是网站必备的功能,如注册验证,忘记密码或者是给用户发送通知信息。早期我们使用JavaMail相关api来写发送邮件。后来spring推出了JavaMailSender简化了邮件发送的过程,再之后springboot对此进行了封装。
复杂的邮件内容一般使用html,thymeleaf模板可以简化html的生成。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
spring.mail.host=smtp.exmail.qq.comspring.mail.username=noreply@qyqq.comspring.mail.password=password123456spring.mail.default-encoding=UTF-8#spring.mail.properties.mail.smtp.starttls.enable=true#spring.mail.properties.mail.smtp.starttls.required=true#spring.mail.properties.mail.smtp.socketFactory.port=465#spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory#spring.mail.properties.mail.smtp.ssl.trust=smtp.exmail.qq.com#spring.mail.properties.mail.smtp.connectiontimeout=30000#spring.mail.properties.mail.smtp.timeout=30000#spring.mail.properties.mail.smtp.writetimeout=20000
import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.stereotype.Service;@Servicepublic class MailService {@Value("${spring.mail.username}")//from address must be same as authorization userString mailFrom;@AutowiredJavaMailSender mailSender;public void sendHtml(String mailTo, String subject, String html) throws MessagingException{MimeMessage mime = mailSender.createMimeMessage();MimeMessageHelper mail = new MimeMessageHelper(mime);mail.setFrom(mailFrom);mail.setTo(mailTo.split(";"));//支持多个接收者mail.setSubject(subject);mail.setText(html, true);mailSender.send(mime);}}
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.thymeleaf.TemplateEngine;import org.thymeleaf.context.Context;@Servicepublic class NotifyService {@Autowiredprivate MailService mailService;@Autowiredprivate TemplateEngine templateEngine;public void sendNotify(String mailTo, String subject, Context context) {new Thread(() -> {//开启线程异步发送邮件try {String html = templateEngine.process("mail/notify", context);mailService.sendHtml(mailTo, subject, html);//TODO: 发送成功} catch (Exception e) {//TODO: 发送失败e.printStackTrace();}}).start();}}
