可能有人会说了,发送邮件多么简单,我单手十分钟就可以写完。大佬避让,我是萌新,所以发送邮件也从最简单的说起。
因为本人是在springboot中发送邮件,所以采用spring提供的邮件解决方案,在maven中引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
根据springboot自动配置的特性,此时邮件其实就已经可以用了,但是我们知道,发送邮件肯定需要smtp服务,所以在发送之前,还得配置上自己的smtp服务的信息。
spring.mail.host=smtp.qq.com
spring.mail.port=25
[email protected]
spring.mail.password=********
spring.mail.protocol=smtp
这里我使用的是qq邮箱提供的smtp服务,最好不要自己搭建邮件服务器,因为肯定会被扔进垃圾箱里面。
然后,就可以使用下面的代码直接发送邮件了。
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg);
helper.setFrom(from);
helper.setTo(email);
helper.setSubject(subject);
helper.setText(contant);
javaMailSender.send(msg);
当然,如果你不满足于发纯文本的邮件,也可以接着看下面的内容,引入 thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
用thymeleaf来做模板,我们可以发送html给用户。例如,我要发送一个验证码给用户
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<div>
<span>发给您的验证码为</span>
</div>
<div>
<h2 th:text="${code}"></h2>
</div>
</body>
</html>
这里 th:text="" 是thymeleaf里面的语法,语法简单,容易上手。
然后,在服务中调用的方式为:
@Service
public class SendEmailServiceImpl implements SendEmailService {
private static final String EMAIL_TEMPLATE_ENCODING = "UTF-8";
@Autowired
MathematicalService mathematicalService;
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
String from;
@Override
public String sendEmail(String email, String subject) throws MessagingException {
String code = mathematicalService.getVerificationCode();
try {
synchronized (this){
if (!templateEngine.isInitialized())templateEngine.addTemplateResolver(htmlTemplateResolver());
}
}catch (Exception ex){
ex.printStackTrace();
}
final Context context = new Context();
context.setVariable("code", code);
final String contant = templateEngine.process("mail/VerificationCode", context);
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true);
helper.setFrom(from);
helper.setTo(email);
helper.setSubject(subject);
helper.setText(contant, true);
javaMailSender.send(msg);
return code;
}
private synchronized ITemplateResolver htmlTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setOrder(Integer.valueOf(2));
templateResolver.setResolvablePatterns(Collections.singleton("mail/*"));
templateResolver.setPrefix("/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING);
templateResolver.setCacheable(false);
return templateResolver;
}
}
你也可以写更复杂的html给用户,详情可以参考thymeleaf官网文档中的方法。