场景

甲客户访问B的公司官网时,发现乙公司的产品可以引进,所以想通过官网客户留言的方式与乙沟通。
客户在某公司官网留言是不需要登录邮箱的,甲客户填入自己的留言,点击提交。这时候就需要乙公司的A邮箱发送邮件到乙公司的B邮箱,邮件内容为甲客户的留言信息。
发送人和接收人均为乙公司,只不过使用不同的邮箱

springboot集成的mail

这种方式发送邮件,需要几个必需的参数:发送人邮箱服务器(host)、发送人账号(username)、发送人授权码(password)。
邮箱服务器可以去搜索一下,qq邮箱:smtp.qq.com 163邮箱:smtp.163.com
授权码,需要登录发送人邮箱,从账号设置里面进行获取,开通POP3/SMTP提供的授权码,如果没有授权码,使用真实密码
我用的是163的邮箱,所以以163的为例子

引入maven依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

配置application.yml

1
2
3
4
5
6
7
spring:
mail:
host: smtp.163.com
username: zhansan@163.com #改成自己的
password: KIRLYASCYAZIOZHD #改成自己的
protocol: smtp
default-encoding: UTF-8

编写邮件工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import com.dakj.entity.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

public class EmailUtils {

@Autowired
private JavaMailSender mailSender;

public String sendEmail(@RequestBody Email email) {

String customerName = "李先生";
String customerTelphone = "15088888888";
String customerContent = "看了下你们的产品,我很满意,可以一起合作吗?";

//客户留言信息
String content = "\n客户姓名:" + customerName + "\n客户手机:" + customerTelphone + "\n客户问题:" + customerContent;

SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
// 发送人邮件地址
simpleMailMessage.setFrom("zhangsan111@163.com");
// 收件人邮件地址
simpleMailMessage.setTo("zhangsan222@163.com");
// 邮件主题
simpleMailMessage.setSubject("==== 客户留言 ====");
// 邮件内容
simpleMailMessage.setText(content);
// 发送邮件
mailSender.send(simpleMailMessage);
return "发送邮件成功!";
}
}

springboot集成的mail(自定义邮件模板模式)

引入maven依赖

1
2
3
4
5
6
7
8
9
10
11
<!-- mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

创建application.yml文件

1
2
3
4
5
6
7
8
spring:
mail:
host: smtp.qq.com # QQ邮箱smtp主机
port: 587 #端口号465或587
username: test@qq.com
password: asdadazxqsdas # 这里QQ邮箱开通POP3/SMTP提供的授权码,如果邮箱服务商没有授权码,可以使用密码代替
protocol: smtp
default-encoding: UTF-8

创建springboot-email启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import cn.tyrone.springboot.mail.util.MailBean;
import cn.tyrone.springboot.mail.util.MailUtil;

@SpringBootApplication
public class Application implements CommandLineRunner {

private static final Logger log = LoggerFactory.getLogger(Application.class);

@Autowired MailUtil mailUtil;
// 注入模板引擎
@Autowired TemplateEngine templateEngine;

public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}

@Override
public void run(String... args) throws Exception {
log.info("------------- SpringBoot集成JavaMail实现邮件发送开始 -------------");
MailBean mailBean = MailBean.getMailBean();
/*
* 简易邮件发送测试
*/
// mailBean.setSubject("SpringBoot集成JavaMail实现邮件发送");
// mailBean.setText("SpringBoot集成JavaMail实现简易邮件发送功能");
// mailUtil.sendMail(mailBean);

/**
* HTML邮件正文发送测试
*/
// String html =
// "<html>"
// + "<body>"
// + "<p><h1>SpringBoot集成JavaMail实现正文为HTML的邮件发送功能</h1></p>"
// + "</body>"
// + "</html>";
// mailBean.setSubject("SpringBoot集成JavaMail实现邮件发送");
// mailBean.setText(html);
// mailUtil.sendMailHtml(mailBean);

/**
* 附件邮件发送测试
*/
// String filePath="/Users/shanglishuai/Downloads/Jietu20180727-144621@2x.jpg";
// FileSystemResource file = new FileSystemResource(new File(filePath));
// String attachmentFilename = filePath.substring(filePath.lastIndexOf(File.separator));
// mailBean.setSubject("SpringBoot集成JavaMail实现邮件发送");
// mailBean.setText("SpringBoot集成JavaMail实现附件邮件发送");
// mailBean.setFile(file);
// mailBean.setAttachmentFilename(attachmentFilename);
// mailUtil.sendMailAttachment(mailBean);


/**
* 内联资源邮件发送测试
*/
// String filePath="/Users/shanglishuai/Downloads/Jietu20180727-144621@2x.jpg";
// String contentId = UUID.randomUUID().toString().replace("-", "");
// /*
// * <img src=\'cid:" + contentId + "\' >
// * cdi:是固定的,其后连接内联资源的的ID(保证唯一即可)
// */
// String content = "<html><body>内联资源邮件发送:<img src=\'cid:" + contentId + "\' ></body></html>";
// FileSystemResource file = new FileSystemResource(new File(filePath));
// mailBean.setSubject("SpringBoot集成JavaMail实现邮件发送");
// mailBean.setText(content);
// mailBean.setFile(file);
// mailBean.setContentId(contentId);
// mailUtil.sendMailInline(mailBean);

Context context = new Context();
context.setVariable("user", "Tyrone");
String content = templateEngine.process("emailTemplate", context);
mailBean.setSubject("SpringBoot集成JavaMail实现邮件发送");
mailBean.setText(content);
mailUtil.sendMailTemplate(mailBean);

log.info("------------- SpringBoot集成JavaMail实现邮件发送结束 -------------");
}
}

为了便于测试,启动类直接实现CommandLineRunner接口,并重写run方法来实现邮件发送的测试

创建发送邮件工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class MailUtil {

@Autowired
private JavaMailSender mailSender; // 自动注入的Bean

@Value("${spring.mail.username}")
private String sender; // 读取配置文件中的参数

/**
* 发送邮件测试方法
*/
public void sendMail() {
SimpleMailMessage mimeMessage = new SimpleMailMessage();
mimeMessage.setFrom(sender);
mimeMessage.setTo(sender);
mimeMessage.setSubject("SpringBoot集成JavaMail实现邮件发送");
mimeMessage.setText("SpringBoot集成JavaMail实现邮件发送正文");
mailSender.send(mimeMessage);
}

/**
* 发送简易邮件
* @param mailBean
*/
public void sendMail(MailBean mailBean) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

try {
helper.setFrom(sender);
helper.setTo(sender);
helper.setSubject(mailBean.getSubject());
helper.setText(mailBean.getText());
} catch (MessagingException e) {
e.printStackTrace();
}

mailSender.send(mimeMessage);
}

/**
* 发送邮件-邮件正文是HTML
* @param mailBean
*/
public void sendMailHtml(MailBean mailBean) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

try {
helper.setFrom(sender);
helper.setTo(sender);
helper.setSubject(mailBean.getSubject());
helper.setText(mailBean.getText(), true);
} catch (MessagingException e) {
e.printStackTrace();
}

mailSender.send(mimeMessage);
}
/**
* 发送邮件-附件邮件
* @param mailBean
*/
public void sendMailAttachment(MailBean mailBean) {
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(sender);
helper.setTo(sender);
helper.setSubject(mailBean.getSubject());
helper.setText(mailBean.getText(), true);
// 增加附件名称和附件
helper.addAttachment(mailBean.getAttachmentFilename(), mailBean.getFile());
mailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}

/**
* 内联资源(静态资源)邮件发送
* 由于邮件服务商不同,可能有些邮件并不支持内联资源的展示
* 在测试过程中,新浪邮件不支持,QQ邮件支持
* 不支持不意味着邮件发送不成功,而且内联资源在邮箱内无法正确加载
* @param mailBean
*/
public void sendMailInline(MailBean mailBean) {
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(sender);
helper.setTo(sender);
helper.setSubject(mailBean.getSubject());

/*
* 内联资源邮件需要确保先设置邮件正文,再设置内联资源相关信息
*/
helper.setText(mailBean.getText(), true);
helper.addInline(mailBean.getContentId(), mailBean.getFile());

mailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}

/**
* 模板邮件发送
* @param mailBean
*/
public void sendMailTemplate(MailBean mailBean) {
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(sender);
helper.setTo(sender);
helper.setSubject(mailBean.getSubject());
helper.setText(mailBean.getText(), true);
mailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}

}

创建Mail实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import org.springframework.core.io.FileSystemResource;
import lombok.Data;

/**
* 邮件实体类
* @author shanglishuai
*/
@Data
public class MailBean {
/**
* 邮件主题
*/
private String subject;
/**
* 邮件内容
*/
private String text;
/**
* 附件
*/
private FileSystemResource file;
/**
* 附件名称
*/
private String attachmentFilename;
/**
* 内容ID,用于发送静态资源邮件时使用
*/
private String contentId;

public static MailBean getMailBean() {
return new MailBean();
}

}

创建邮件模板文件

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<p>Hello!<span th:text="${user}"></span>!<br /></p>
这是SpringBoot集成Java Email,并通过Thymeleaf创建邮件模板,实现的模板邮件发送!!!
</body>
</html>

注意:根据约定大于配置,模板文件建议放在resources目录下。本例:/resources/templates/emailTemplate.html