pom包配置
<!--郵件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--freemarker模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
模板引擎配置
spring:
freemarker:
template-loader-path: classpath:/templates/
郵件服務器的配置
spring:
mail
host: smtp.qq.com
username: xxx@qq.com
password: cumhxmicujosbjii #開啟POP3之后設置的客戶端授權碼
default-encoding: UTF-8
簡單的文本郵件
@Override
public void sendSimpleMail(String to, String subject, String content) throws MailException {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); // 郵件發(fā)送者
message.setTo(to); // 郵件接受者
message.setSubject(subject); // 主題
message.setText(content); // 內容
mailSender.send(message);
}
發(fā)送帶圖片的郵件
controller的代碼
@ApiOperation(value = "html郵件測試" , notes="html郵件測試")
@GetMapping("/testHtml")
public ResultVo testHtml() throws IOException, TemplateException, MessagingException {
Map<String, Object> model = new HashMap();
model.put("UserName", "yao");
Template template = configuration.getTemplate("welcome.ftl");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
emailService.sendHtmlMail("249982536@163.com","html郵件",html);
return ResultUtils.success();
}
service的代碼
@Override
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
//true 表?示需要創(chuàng)建?一個 multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
}