版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fooelliot/article/details/86567952
spring-boot-mail
开发环境
开发工具:Intellij IDEA 2018.2.6
springboot: 2.0.7.RELEASE
jdk:1.8.0_192
maven: 3.6.0
spring-boot-mail
SpringBoot 有提供发送邮件的实现,整合也非常方便只需要引入 SpringBoot 整合mail 的 starter 就可以使用 JavaMailSender 封装好的api实现发送邮件的功能。本文使用了freemarker 和thymeleaf 两种模板引擎技术来实现发送模板类型的邮件。
pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>com.andy</groupId>
<artifactId>spring-boot-mail</artifactId>
<version>1.0.7.RELEASE</version>
<modelVersion>4.0.0</modelVersion>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>Cairo-SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--生成二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.0.6.RELEASE</version>
<configuration>
<!--<mainClass>${start-class}</mainClass>-->
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
- 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author Leone
* @since 2018-05-09
**/
@SpringBootApplication
public class MailApplication {
public static void main(String[] args) {
SpringApplication.run(MailApplication.class, args);
}
}
- freemarker 模板(ftlMail.ftl)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div style="width: 600px; text-align: left; margin: 0 auto;">
<h3 style="color: #005da7;">您好!${(to)!""}</h3>
<div style="border-bottom: 5px solid #005da7; height: 2px; width: 100%;"></div>
<div style="border: 1px solid #005da7; font-size: 16px; line-height: 50px; padding: 20px;">
<div>
欢迎注册xxx!
</div>
<div style="border-bottom: 2px solid #005da7; height: 2px; width: 100%;"></div>
<div>点击链接激活您的账号!</div>
<div>
<span><a href="${(content)!""}">激活</a></span>
</div>
<div>
<img src="https://www.baidu.com/img/xinshouye_7c5789a51e2bfd441c7fe165691b31a1.png" alt="baidu"/>
</div>
<div>
想了解更多信息,请访问 <a href="https://www.baidu.com/">https://www.baidu.com/</a>
</div>
</div>
</div>
</body>
</html>
- thymeleaf 模板(htmlMail.html)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div style="width: 600px; text-align: left; margin: 0 auto;">
<h1>XXX</h1>
<div style="border-bottom: 5px solid #005da7; height: 2px; width: 100%;"></div>
<div style="border: 1px solid #005da7; font-size: 16px; line-height: 50px; padding: 20px;">
<div>
<p th:text="${to}+' 您好,欢迎注册xxx!!'"></p>
</div>
<div style="border-bottom: 2px solid #005da7; height: 2px; width: 100%;"></div>
<div>请点击下面链接激活您的账号!</div>
<div>
<span><a th:href="${content}">激活</a></span>
</div>
<div>
<img src="https://www.baidu.com/img/xinshouye_7c5789a51e2bfd441c7fe165691b31a1.png" alt="baidu"/>
</div>
<div>
想了解更多信息,请访问 <a href="https://www.baidu.com/">https://www.baidu.com/</a>
</div>
</div>
</div>
</body>
</html>
- application.yml
server:
port: 8083
servlet:
path: /
spring:
application:
name: spring-boot-mail
http:
encoding:
charset: UTF-8
enabled: true
# JavaMailSender 邮件发送的配置 我使用的163邮箱作为发送方
mail:
host: smtp.163.com
username: [email protected]
password: xxx
properties:
mail:
smtp:
auth: true
starttls:
enabled: true
required: true
default-encoding: UTF-8
# thymeleaf 配置
thymeleaf:
cache: false
prefix: classpath:/templates/thymeleaf
suffix: .html
mode: HTML
encoding: UTF-8
servlet:
content-type: text/html
# freemarker配置
# freemarker:
# template-loader-path: classpath:/templates/freemarker/
# allow-request-override: false
# cache: false
# suffix: .ftl
# charset: UTF-8
# content-type: text/html
# check-template-location: true
# expose-request-attributes: false
# expose-session-attributes: false
# expose-spring-macro-helpers: false
- MailService.java
package com.andy.mail.service;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* @author Leone
* @since 2018-05-09
**/
@Slf4j
@Service
public class MailService {
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private TemplateEngine templateEngine;
// @Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
private static final Charset CHARSET = StandardCharsets.UTF_8;
private static final String THYMELEAF_TEMPLATE = "/htmlMail";
private static final String FREEMARKER_TEMPLATE = "ftlMail.ftl";
private static final String filePath = "hello.zip";
/**
* 发送freemarker模板mail
*
* @param to
* @param subject
* @return
* @throws Exception
*/
public boolean sendFreemarkerMail(String to, String subject, String content) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(InternetAddress.parse(to));
helper.setSubject("[" + subject + " " + LocalDate.now() + "]");
Map<String, Object> model = new HashMap<>();
model.put("subject", subject);
model.put("content", content);
model.put("to", to);
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(FREEMARKER_TEMPLATE);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
helper.setText(text, true);
javaMailSender.send(mimeMessage);
log.info("send mail success!");
return true;
} catch (Exception e) {
log.error("send mail filed:{}", e);
return false;
}
}
/**
* 发送thymeleaf邮件
*
* @param to
* @param subject
* @return
* @throws Exception
*/
public boolean sendThymeleafMail(String to, String subject, String content) {
// String token = storage(to);
String token = "xxx";
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, CHARSET.displayName());
Map<String, Object> map = new HashMap<>();
map.put(content, token);
map.put("content", content);
map.put("subject", subject);
map.put("to", to);
IContext context = new Context(Locale.CHINESE, map);
String process = templateEngine.process(THYMELEAF_TEMPLATE, context);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject("[" + subject + " " + LocalDate.now() + "]");
messageHelper.setText(process, true);
javaMailSender.send(mimeMessage);
log.info("send mail success!");
return true;
} catch (Exception e) {
log.error("send mail filed:{}", e);
e.printStackTrace();
return false;
}
}
/**
* 发送文本邮件
*
* @param to
* @param subject
* @param content
*/
public boolean sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
javaMailSender.send(message);
log.info("send mail success!");
return true;
} catch (Exception e) {
log.error("send mail filed:{}", e);
return false;
}
}
/**
* 发送带附件的邮件
*
* @param to
* @param subject
* @param content
*/
public boolean sendAttachmentsMail(String to, String subject, String content) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
//helper.addAttachment("test"+fileName, file);
javaMailSender.send(message);
log.info("send mail success!");
return true;
} catch (MessagingException e) {
log.error("send mail filed:{}", e);
return false;
}
}
/**
* 发送正文中有静态资源(图片)的邮件
*
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId
*/
public boolean sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
javaMailSender.send(message);
log.info("send mail success!");
return true;
} catch (MessagingException e) {
log.error("send mail filed:{}", e);
return false;
}
}
}
- MailController.java
package com.andy.mail.controller;
import com.andy.mail.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @author Leone
* @since 2018-05-09
**/
@Slf4j
@Controller
@RequestMapping("/api/mail")
public class MailController {
@Autowired
private MailService mailService;
private static Map<String, Object> content = new HashMap<>();
static {
content.put("title", "标题");
content.put("content", "http://www.baidu.com");
content.put("to", "[email protected]");
}
@ResponseBody
@GetMapping("/send/ftl")
public String sendFtlMain(String to, String subject, String content, HttpServletRequest request) {
boolean flag = mailService.sendFreemarkerMail(to, subject, content);
return String.valueOf(flag);
}
@ResponseBody
@GetMapping("/send/html")
public String sendHtmlMain(String to, String subject, String content, HttpServletRequest request) {
boolean flag = mailService.sendThymeleafMail(to, subject, content);
return String.valueOf(flag);
}
@ResponseBody
@GetMapping("/send/simple")
public String sendSimpleMain(String to, String subject, String content, HttpServletRequest request) {
boolean flag = mailService.sendSimpleMail(to, subject, content);
return String.valueOf(flag);
}
@ResponseBody
@GetMapping("/send/htm")
public String sendAttachmentsMail(String to, String subject, String content, HttpServletRequest request) {
boolean flag = mailService.sendAttachmentsMail(to, subject, content);
return String.valueOf(flag);
}
@RequestMapping("/html")
public String helloHtml(Map<String, Object> map) {
map.putAll(content);
return "/htmlMail";
}
@RequestMapping("/ftl")
public String helloFtl(Map<String, Object> map) {
map.putAll(content);
return "ftlMail";
}
}