在项目的维护过程中,通常会加入邮箱的报警功能,当系统出现异常、宕机等问题时,及时能将问题以邮箱的形式发送给运维或
者开发人员,从而快速解决系统问题,保证系统的正常运行。
本文中将mail整合到springboot中,实现邮件的发送。在springboot中发送邮件中,使用的是spring所提供的包
org.springframework.mail.javamail.JavaMailSender,该包中提供了许多简单易容的方法,发送邮件的方式有多种,如:简单的
邮件、HTML格式的邮件、带附件的邮件。
springboot整合邮件的步骤如下:
1、引入依赖
本版号:
springContext.version:5.1.3.RELEASE
mail.version:1.4.7
beetl.version:2.9.7
<!--邮件发送依赖包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springContext.version}</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${mail.version}</version>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>${beetl.version}</version>
</dependency>
2、添加配置文件(yml文件配置方式)
username为邮箱地址,password为邮箱授权码(邮箱授权码获取方式如下图所示)。
spring:
# spring整合email配置
mail:
host: smtp.qq.com
username: XXXXXX@qq.com
password: XXXXXX
邮箱授权码获取方式(以QQ邮箱为例):
3、添加配置类,实现邮箱的发送
配置类:
package com.aaron.config.email;
import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.io.IOException;
/**
* @author: Aaron
* @description: 邮件配置
* @date: Create in 2019/5/23 下午 04:43
*/
@Configuration
@ComponentScan(value = "com.aaron.utils")
public class EmailConfig {
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String authWord;
/**
* 在这里可以声明不同的邮件服务器主机,
* 通常是SMTP主机,而具体的用户名和时授权码则建议在业务中从数据库查询
*
* @return
*/
@Bean(name = "mainSender")
JavaMailSenderImpl javaMailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
// 设置发送人邮箱和授权码
javaMailSender.setUsername(username);
javaMailSender.setPassword(authWord);
return javaMailSender;
}
/**
* 配置模板引擎
*
* @return
* @throws IOException
*/
@Bean
GroupTemplate groupTemplate() throws IOException {
// 指定加载模板资源的位置 指定在classpath:beetl下
ClasspathResourceLoader loader = new ClasspathResourceLoader("beetl");
// beetl配置 这里采用默认的配置
org.beetl.core.Configuration configuration = org.beetl.core.Configuration.defaultConfiguration();
return new GroupTemplate(loader, configuration);
}
}
工具类:
package com.aaron.utils;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;
/**
* @author: Aaron
* @description:
* @date: Create in 2019/5/23 下午 04:44
*/
@Component
public class EmailUtil {
@Autowired
private JavaMailSenderImpl mailSender;
@Autowired
private GroupTemplate groupTemplate;
@Value("${spring.mail.username}")
private String username;
/**
* @param to
* @param subject
* @param content
* @description: 发送简单邮件
*/
public void sendTextMessage(String to, String subject, String content) {
// 实例化消息对象
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(username);
msg.setTo(to);
msg.setSubject(subject);
msg.setText(content);
try {
// 发送消息
this.mailSender.send(msg);
System.out.println("邮件发送成功");
} catch (MailException e) {
System.out.println("邮件发送失败:" + e.getMessage());
}
}
/**
* @param to
* @param subject
* @param content
* @param files
* @description: 发送带附件的邮件
*/
public void sendEmailWithAttachments(String to, String subject,
String content, Map<String, File> files) {
try {
// 实例化消息对象
MimeMessage message = mailSender.createMimeMessage();
// 需要指定第二个参数为true 代表创建支持可选文本,内联元素和附件的多部分消息
MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
helper.setFrom(username);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content);
// 传入附件
for (Map.Entry<String, File> entry : files.entrySet()) {
helper.addAttachment(entry.getKey(), entry.getValue());
}
// 发送消息
this.mailSender.send(message);
System.out.println("邮件发送成功");
} catch (MessagingException e) {
System.out.println("邮件发送失败:" + e.getMessage());
}
}
/**
* @param to
* @param subject
* @param content
* @param file
* @description: 发送带内嵌资源的邮件
*/
public void sendEmailWithInline(String to, String subject, String content, File file) {
try {
// 实例化消息对象
MimeMessage message = mailSender.createMimeMessage();
// 需要指定第二个参数为true 代表创建支持可选文本,内联元素和附件的多部分消息
MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
helper.setFrom(username);
helper.setTo(to);
helper.setSubject(subject);
// 使用true标志来指示包含的文本是HTML 固定格式资源前缀 cid:
helper.setText("<html><body><img src='cid:image'></body></html>", true);
// 需要先指定文本 再指定资源文件
FileSystemResource res = new FileSystemResource(file);
helper.addInline("image", res);
// 发送消息
this.mailSender.send(message);
System.out.println("邮件发送成功");
} catch (MessagingException e) {
System.out.println("邮件发送失败:" + e.getMessage());
}
}
/**
* @param to
* @param subject
* @param content
* @description: 使用模板邮件
*/
public void sendEmailByTemplate(String to, String subject, String content) {
try {
Template t = groupTemplate.getTemplate("template.html");
t.binding("subject", subject);
t.binding("content", content);
String text = t.render();
// 实例化消息对象
MimeMessage message = mailSender.createMimeMessage();
// 指定 utf-8 防止乱码
MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
helper.setFrom(username);
helper.setTo(to);
helper.setSubject(subject);
// 为true 时候 表示文本内容以 html 渲染
helper.setText(text, true);
this.mailSender.send(message);
System.out.println("邮件发送成功");
} catch (MessagingException e) {
// 消息发送失败可以做对应的处理
System.out.println("邮件发送失败:" + e.getMessage());
}
}
}
html模板(本文中使用beetl模板),放在resources目录下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>邮件主题:<span style="color: chartreuse"> ${subject}</span></h1>
<h4 style="color: blueviolet">${content}</h4>
</body>
</html>
4、通过测试,验证邮件是否发送成功。
单元测试类:
package com.aaron.emailtest;
import com.aaron.utils.EmailUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* @author: Aaron
* @description:
* @date: Create in 2019/5/23 下午 05:32
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {
@Autowired
private EmailUtil emailUtil;
// 接收方邮箱地址
private static final String to = "XXXXXX@qq.com";
/**
* 发送简单邮件
*/
@Test
public void sendMessage() {
emailUtil.sendTextMessage(to, "发送简单邮件", "Hello Spring Email");
}
/**
* 发送带附件的邮件
*/
@Test
public void sendEmailWithAttachments() {
Map<String, File> fileMap = new HashMap<>();
fileMap.put("image1.jpg", new File("E:\\Aaron\\picture\\附件1.png"));
fileMap.put("image2.jpg", new File("E:\\Aaron\\picture\\附件2.png"));
emailUtil.sendEmailWithAttachments(to, "发送带附件的邮件"
, "Hello Spring Email", fileMap);
}
/**
* 发送带内嵌资源的邮件
*/
@Test
public void sendEmailWithInline() {
emailUtil.sendEmailWithInline(to, "发送带内嵌资源的邮件"
, "Hello Spring Email", new File("E:\\Aaron\\picture\\附件3.png"));
}
/**
* 使用模板邮件
*/
@Test
public void sendEmailByTemplate() {
emailUtil.sendEmailByTemplate(to, "使用模板邮件", "Hello Spring Email");
}
}
测试结果: