Skip to content

Commit 4493d0c

Browse files
committed
SpringBoot之javaMail发送,支持Freemark模板
1 parent dfb86af commit 4493d0c

File tree

10 files changed

+346
-0
lines changed

10 files changed

+346
-0
lines changed

chapter11/.gitignore

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/target/
2+
!.mvn/wrapper/maven-wrapper.jar
3+
4+
### STS ###
5+
.apt_generated
6+
.classpath
7+
.factorypath
8+
.project
9+
.settings
10+
.springBeans
11+
.sts4-cache
12+
13+
### IntelliJ IDEA ###
14+
.idea
15+
*.iws
16+
*.iml
17+
*.ipr
18+
19+
### NetBeans ###
20+
/nbproject/private/
21+
/build/
22+
/nbbuild/
23+
/dist/
24+
/nbdist/
25+
/.nb-gradle/

chapter11/pom.xml

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>com.yukong</groupId>
7+
<artifactId>mail</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>jar</packaging>
10+
11+
<name>mail</name>
12+
<description>springboot for send mail</description>
13+
14+
<parent>
15+
16+
<groupId>org.springframework.boot</groupId>
17+
<artifactId>spring-boot-starter-parent</artifactId>
18+
<version>2.1.1.RELEASE</version>
19+
<relativePath/> <!-- lookup parent from repository -->
20+
</parent>
21+
22+
<properties>
23+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
24+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
25+
<java.version>1.8</java.version>
26+
</properties>
27+
28+
<dependencies>
29+
<dependency>
30+
<groupId>org.springframework.boot</groupId>
31+
<artifactId>spring-boot-starter-mail</artifactId>
32+
</dependency>
33+
<dependency>
34+
<groupId>org.springframework.boot</groupId>
35+
<artifactId>spring-boot-starter-web</artifactId>
36+
</dependency>
37+
<dependency>
38+
<groupId>org.springframework.boot</groupId>
39+
<artifactId>spring-boot-starter-test</artifactId>
40+
<scope>test</scope>
41+
</dependency>
42+
<dependency>
43+
<groupId>org.springframework.boot</groupId>
44+
<artifactId>spring-boot-starter-freemarker</artifactId>
45+
</dependency>
46+
</dependencies>
47+
48+
<build>
49+
<plugins>
50+
<plugin>
51+
<groupId>org.springframework.boot</groupId>
52+
<artifactId>spring-boot-maven-plugin</artifactId>
53+
</plugin>
54+
</plugins>
55+
</build>
56+
57+
58+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.yukong.mail;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class MailApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(MailApplication.class, args);
11+
}
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package com.yukong.mail;
2+
3+
import com.yukong.mail.entity.Mail;
4+
import freemarker.template.Template;
5+
import freemarker.template.TemplateException;
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
import org.springframework.beans.factory.InitializingBean;
9+
import org.springframework.beans.factory.annotation.Autowired;
10+
import org.springframework.beans.factory.annotation.Value;
11+
import org.springframework.mail.javamail.JavaMailSender;
12+
import org.springframework.mail.javamail.MimeMessageHelper;
13+
import org.springframework.stereotype.Service;
14+
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
15+
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
16+
17+
import javax.mail.internet.InternetAddress;
18+
import javax.mail.internet.MimeMessage;
19+
import javax.mail.internet.MimeUtility;
20+
import java.io.IOException;
21+
import java.util.HashMap;
22+
import java.util.Map;
23+
24+
/**
25+
* @author: yukong
26+
* @date: 2018/12/5 16:56
27+
*/
28+
@Service
29+
public class MailSendService {
30+
private Logger logger = LoggerFactory.getLogger(getClass());
31+
32+
@Autowired
33+
private JavaMailSender javaMailSender;
34+
35+
@Autowired
36+
private FreeMarkerConfigurer freeMarkerConfigurer;
37+
38+
@Value("${spring.mail.username}")
39+
private String USERNAME = "yukong";
40+
41+
42+
43+
44+
/**
45+
* 根据模板名 获取邮件内容
46+
* @param templateName
47+
* @param params
48+
* @return
49+
*/
50+
private String getMailTextByTemplateName(String templateName, Map<String,Object> params) throws IOException, TemplateException {
51+
String mailText = "";
52+
//通过指定模板名获取FreeMarker模板实例
53+
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
54+
//FreeMarker通过Map传递动态数据
55+
//注意动态数据的key和模板标签中指定的属性相匹配
56+
//解析模板并替换动态数据,最终code将替换模板文件中的${code}标签。
57+
mailText = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
58+
return mailText;
59+
}
60+
61+
public boolean sendWithHTMLTemplate(Mail mail) {
62+
try {
63+
//发件人的昵称
64+
String nick = MimeUtility.encodeText(USERNAME);
65+
//发件人是谁
66+
InternetAddress from = new InternetAddress(nick + "<541130126@qq.com>");
67+
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
68+
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
69+
mimeMessageHelper.setTo(mail.getEmail());
70+
mimeMessageHelper.setFrom(from);
71+
mimeMessageHelper.setSubject(mail.getSubject());
72+
HashMap<String, Object> params = new HashMap<>();
73+
// 使用模板生成html邮件内容
74+
String result =getMailTextByTemplateName(mail.getTemplate(), mail.getParams());
75+
mimeMessageHelper.setText(result, true);
76+
javaMailSender.send(mimeMessage);
77+
return true;
78+
} catch (Exception e) {
79+
logger.error("发送邮件失败" + e.getMessage());
80+
return false;
81+
}
82+
}
83+
84+
85+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.yukong.mail;
2+
3+
/**
4+
* @author: yukong
5+
* @date: 2018/12/5 17:23
6+
*/
7+
public enum MailTemplateNameEnum {
8+
9+
LOGIN_CODE("login_code.ftl", "登录验证码模板");
10+
11+
String code;
12+
13+
String desc;
14+
15+
private MailTemplateNameEnum(String code, String desc) {
16+
this.code = code;
17+
this.desc = desc;
18+
}
19+
20+
public String getCode() {
21+
return code;
22+
}
23+
24+
public String getDesc() {
25+
return desc;
26+
}
27+
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.yukong.mail.entity;
2+
3+
import java.io.Serializable;
4+
import java.util.Map;
5+
6+
/**
7+
* @author: yukong
8+
* @date: 2018/12/5 17:25
9+
*/
10+
public class Mail implements Serializable {
11+
private static final long serialVersionUID = 1L;
12+
//接收方邮件
13+
private String email;
14+
15+
//主题
16+
private String subject;
17+
//模板
18+
private String template;
19+
20+
// 自定义参数
21+
private Map<String, Object> params;
22+
23+
public static long getSerialVersionUID() {
24+
return serialVersionUID;
25+
}
26+
27+
public String getEmail() {
28+
return email;
29+
}
30+
31+
public void setEmail(String email) {
32+
this.email = email;
33+
}
34+
35+
public String getSubject() {
36+
return subject;
37+
}
38+
39+
public void setSubject(String subject) {
40+
this.subject = subject;
41+
}
42+
43+
public String getTemplate() {
44+
return template;
45+
}
46+
47+
public void setTemplate(String template) {
48+
this.template = template;
49+
}
50+
51+
public Map<String, Object> getParams() {
52+
return params;
53+
}
54+
55+
public void setParams(Map<String, Object> params) {
56+
this.params = params;
57+
}
58+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
spring:
2+
mail:
3+
host: smtp.qq.com
4+
username: 541130126@qq.com
5+
password: xxx
6+
properties:
7+
mail:
8+
smtp:
9+
auth: true
10+
starttls:
11+
enable: true
12+
required: true
13+
freemarker:
14+
charset: UTF-8
15+
allow-request-override: false
16+
cache: false
17+
expose-request-attributes: false
18+
expose-session-attributes: false
19+
content-type: text/html
20+
template-loader-path: classpath:/static/template/
21+
expose-spring-macro-helpers: false
22+
check-template-location: true
23+
enabled: true
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
你好,你本次的登录验证码为${code}若非本人操作,请忽略本邮件。
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.yukong.mail;
2+
3+
import org.junit.Test;
4+
import org.junit.runner.RunWith;
5+
import org.springframework.boot.test.context.SpringBootTest;
6+
import org.springframework.test.context.junit4.SpringRunner;
7+
8+
@RunWith(SpringRunner.class)
9+
@SpringBootTest
10+
public class MailApplicationTests {
11+
12+
@Test
13+
public void contextLoads() {
14+
}
15+
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.yukong.mail;
2+
3+
import com.yukong.mail.entity.Mail;
4+
import org.junit.Test;
5+
import org.junit.runner.RunWith;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.boot.test.context.SpringBootTest;
8+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
9+
10+
import java.util.HashMap;
11+
import java.util.Map;
12+
13+
import static org.junit.Assert.*;
14+
15+
/**
16+
* @author: yukong
17+
* @date: 2018/12/5 17:17
18+
*/
19+
@RunWith(SpringJUnit4ClassRunner.class)
20+
@SpringBootTest
21+
public class MailSendServiceTest {
22+
23+
24+
@Autowired
25+
private MailSendService mailSendService;
26+
27+
@Test
28+
public void sendWithHTMLTemplate() {
29+
Map<String, Object> params = new HashMap<>();
30+
// 参数
31+
Integer code = (int)(Math.random()*9+1)*100000;
32+
params.put("code", code);
33+
Mail mail = new Mail();
34+
mail.setEmail("yukonga@vip.qq.com");
35+
mail.setParams(params);
36+
mail.setTemplate(MailTemplateNameEnum.LOGIN_CODE.getCode());
37+
mail.setSubject("登录验证码");
38+
mailSendService.sendWithHTMLTemplate(mail);
39+
}
40+
}

0 commit comments

Comments
 (0)