一、maven项目添加依赖
<!-- 发送邮件 spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- freemarker 模板 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
二、接口编写
service 层
/**
* @Description 发送邮件接口
*/
public interface MailService {
/**
* @Description 发送简单的文本文件,to:收件人 subject:主题 content:内容
* @Param [to, subject, content]
**/
public void sendSimpleMail(String to, String subject, String content);
/**
* @Description 发送html,to:收件人 subject:主题 content:内容
* @Param [to, subject, content]
**/
public void sendHtmlMail(String to, String subject, String content);
/**
* @Description 发送一个带附件的邮件
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param filePath 文件路径
*/
public void sendAttachmentMail(String to, String subject, String content, String filePath);
/**
* @Description 发送一个图片带附件的邮件
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param rscPath 图片
*/
public void sendInlineResourceMail(String to, String subject, String content, String rscPath);
}
serviceImpl
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
/**
*/
@Service
public class MailServiceImpl implements MailService {
// 发送人的用户名,邮箱地址
@Value("${spring.mail.username}")
private String from;
/**
* JavaMailSender 用来发送邮件
* springboot application.properties 文件设置 spring.mail
*/
@Autowired
private JavaMailSender mailSender;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(from);
mailMessage.setTo(to);
mailMessage.setSubject(subject);
mailMessage.setText(content);
mailSender.send(mailMessage);
}
@Override
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(message);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
//将content里面的标签进行处理,否则为正常的文本处理
messageHelper.setText(content, true);
} catch (MessagingException e) {
logger.error("something wrong...");
e.printStackTrace();
}
mailSender.send(message);
}
@Override
public void sendAttachmentMail(String to, String subject, String content, String filePath) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
// 带上附件,参数传true,否则会报错.
// Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(content);
//设置附件
FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
String filename = fileSystemResource.getFilename();
messageHelper.addAttachment(filename, fileSystemResource);
} catch (MessagingException e) {
logger.error("something wrong...");
e.printStackTrace();
} finally {
}
mailSender.send(mimeMessage);
}
@Override
public void sendInlineResourceMail(String to, String subject, String content, String rscPath) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
//带上附件,参数传true,否则会报错.
//Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(content,true);
//构造邮件内部的图片
FileSystemResource file = new FileSystemResource(new File(rscPath));
//对应的图片src路径
messageHelper.addInline("img", file);
} catch (MessagingException e) {
logger.error("something wrong...");
e.printStackTrace();
}
mailSender.send(mimeMessage);
}
}
三、application.propertis 文件配置
springboot 使用邮箱的方式
# QQ/163邮箱
#smtp.163.com smtp.qq.com
#spring.mail.host=smtp.qq.com
#spring.mail.username=账号
#spring.mail.password=授权码
#spring.mail.properties.mail.smtp.auth=true
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.starttls.required=true
#spring.mail.default-encoding=UTF-8
# 腾讯企业邮箱
spring.mail.host=smtp.exmail.qq.com
spring.mail.username=账号
spring.mail.password=密码
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false
#腾讯企业邮箱 端口的写法有些区别
spring.mail.properties.mail.smtp.socketFactory.port=465
QQ授权码获取: POP3/SMTP服务 开启后会得到授权码
163 (网易)开启授权码
XML 配置 FreeMarkerConfigurer / 也可直接创建对象(读取ftl文佳,生成HTML)
<!-- 配置freeMarkerConfigurer进行属性值的注入 -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths" value="classpath:templates" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">1800</prop>模板更新延时
<prop key="default_encoding">UTF-8</prop>
<prop key="locale">zh_CN</prop>
</props>
</property>
</bean>
mail.ftl freeMaker模板编写
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf8">
</head>
<body>
用户名为:<font color='green' size='16'>${name}</font></br>
<font color='blue' size='16'>${id}</font>
</body>
</html>
四、springboot 测试
package com.monitor.application;
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 com.monitor.email.MailService;
/**
* springboot 邮箱测试类
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailSendTest {
@Autowired
private MailService mailService;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
private String to = "123456@qq.com";
//主题
String subject = "主题内容";
@Test
public void test01() {
String content = "一个简单的文本发送";
mailService.sendSimpleMail(to,subject,content);
}
@Test
public void test02() {
String content = "<html> <h1 style=\"color:red \" >一个简单的html发送</h1></html>";
mailService.sendHtmlMail(to,subject,content);
}
@Test
// XML配置:发送html文件,通过freemarker模板构造
public void getFreemarkerByXml() throws IOException, TemplateException {
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("mail.ftl");
// FreeMarker通过Map传递动态数据
Map<String,Object> map = new HashMap<String,Object>();
// 注意动态数据的key和模板标签中指定的属性相匹配
map.put("name","freeMarker 姓名");
map.put("id","ID:456125");
// 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。
String htmlTxt = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
mailService.sendHtmlMail(to, subject , htmlTxt);
}
@Test
// 创建对象:通过freemarker模板构造邮件内容
public void getFreemarkerByObject() throws IOException, TemplateException {
// 通过指定模板名获取FreeMarker模板实例
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
Properties settings = new Properties();
settings.setProperty("locale", "zh_CN");
settings.setProperty("default_encoding", "UTF-8");
freeMarkerConfigurer.setFreemarkerSettings(settings);
String path = System.getProperty("user.dir"); // 获取项目根目录
FileTemplateLoader ftl1 = new FileTemplateLoader(new File(path + "\\src\\main\\resources\\templates")); // 拼接上自己对应的模板位置
ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "");
TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ctl }; // 可配置多个路径, ftl2,ftl3 ,添加在{} 里面即可.
MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28); // 根据自己引入的版本设置
configuration.setTemplateLoader(mtl);
freeMarkerConfigurer.setConfiguration(configuration);
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("mail.ftl");
// FreeMarker通过Map传递动态数据
Map<String,Object> map = new HashMap<String,Object>();
// 注意动态数据的key和模板标签中指定的属性相匹配
map.put("name","freeMarker 姓名");
map.put("id","ID456125");
// 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。
String htmlTxt = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
mailService.sendHtmlMail(to, subject , htmlTxt);
}
@Test
public void test04() {
String content = "一个简单的带附件发送";
String filePath = "C:\\Users\\DELL\\Desktop\\Test.docx";
mailService.sendAttachmentMail(to,subject,content,filePath);
}
@Test
//发送图片
public void test05() {
//src对应img
String content = "<html><body>一个简单的图片发送:<img src=\'cid:img" + "\'></img></body></html>";
//图片地址
String filePath = "D:\\head.png";
mailService.sendInlineResourceMail(to,subject,content,filePath);
}
}