最近需要做一个邮件发送功能,由于使用微服务,所以就准备先写一个邮件发送demo,利用spring boot 集成的邮件发送,仅供学习,
1配置 gradle
...
dependencies {
...
compile('org.springframework.boot:spring-boot-starter-mail')
compile ('org.freemarker:freemarker:2.3.23')
...
2.添加邮件配置bootstrap.yml
已实锤,就配置这么几个,而且spring boot会自动加载这些参数
spring:
mail:
host: mail.XXX.com
port: 25
default-encoding: UTF-8
3.配置其他参数application.yml
mail:
fromMail:
addr: WECHAT@XX.com
templatePath: /mail
templateName:
test: test.ftl
4.建立模板
模板内容
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;chartset=utf-8"; >
</head>
<body>
尊敬的XX用户: <br/>
您好! 感谢您选择XX<br/>
<font size=20 color='red'>
${content}
<img src="cid:contentImage0">
</font>
</body>
</html>
5.创建发送服务类
接口 MailService
package com.generalichina.wolong.service.mail;
import java.io.File;
import java.util.Map;
public interface MailService {
String getTempletHtmlContent(String templateName, Map<String, String> model) ;
Boolean sendMail(String subject,String[] toWhos,String content,String[] ccPeoples,String[] bccPeoples,File[] attachments,File[] contentImages);
}
实现类MailServiceImpl
package com.generalichina.wolong.service.mail;
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.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.IOException;
import java.util.Map;
/**
* 邮件服务,实现简单文本邮件,HTML文件和附件邮件,模板邮件的发送
* 支持的环境:JDK 1.8,SpringBoot 1.5.10,需要 mail-start,需要 freemaker模板支持
*
* @author qsnp236
*
*/
@Service
public class MailServiceImpl implements MailService{
//默认编码
public static final String DEFAULT_ENCODING = "UTF-8";
//记录日志
private static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
//发送邮件邮箱地址
@Value("${mail.fromMail.addr}")
private String from;
//邮件模板加载路径 resources路径下 /mail
@Value("${mail.templatePath}")
private String templatePath;
//邮件服务器端口 25
@Value("${spring.mail.port}")
private String port;
//邮件服务器地址 mail.XXXa.com
@Value("${spring.mail.host}")
private String host;
//邮件发送的对象,用于邮件发送
@Autowired
private JavaMailSender mailSender;
/**
* 填充并获取模板内容
* @param templateName
* @param model
* @return
*/
public String getTempletHtmlContent(String templateName, Map<String, String> model) {
//模板消息
String content ="";
//创建freemarker配置
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
//模板加载器 templatePath= /mail
TemplateLoader templateLoader=new ClassTemplateLoader(MailServiceImpl.class,templatePath);
//设置加载
cfg.setTemplateLoader(templateLoader);
if(templateName!=null)
{
try {
// 获取模版对象 DEFAULT_ENCODING UTF-8
Template template = cfg.getTemplate(templateName,DEFAULT_ENCODING);
//获取渲染后的文件内容
content = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
} catch ( IOException | TemplateException e) {
e.printStackTrace();
}
}
return content;
}
/**
* 本系统调用
* @param subject
* @param toWhos
* @param templateName
* @param model
* @param ccPeoples
* @param bccPeoples
* @param attachments
* @param contentImages
* @return
*/
public Boolean sendMail(String subject,String[] toWhos,String templateName,Map<String, String> model,String[] ccPeoples,String[] bccPeoples,File[] attachments,File[] contentImages) {
String content=this.getTempletHtmlContent(templateName, model);
return this.sendMail(subject, toWhos, content, ccPeoples, bccPeoples, attachments, contentImages);
}
/**
* 通用最全参数调用
* @param subject NOT NULL
* @param toWhos NOT NULL
* @param content NOT NULL
* @param ccPeoples NULL
* @param bccPeoples NULL
* @param attachments NULL
* @param contentImages NULL
* @return
*/
public Boolean sendMail(String subject,String[] toWhos,String content,String[] ccPeoples,String[] bccPeoples,File[] attachments,File[] contentImages) {
return this.sendMailBaseMethod(subject, toWhos, content, ccPeoples, bccPeoples, attachments, contentImages);
}
/**
* 通用没有正文内嵌图片发送
* @param subject
* @param toWhos
* @param content
* @param ccPeoples
* @param bccPeoples
* @param attachments
* @return
*/
public Boolean sendMail(String subject,String[] toWhos,String content,String[] ccPeoples,String[] bccPeoples,File[] attachments) {
return this.sendMail(subject, toWhos, content, ccPeoples, bccPeoples, attachments, null);
}
/**
* 通用没有附件
* @param subject
* @param toWhos
* @param content
* @param ccPeoples
* @param bccPeoples
* @return
*/
public Boolean sendMail(String subject,String[] toWhos,String content,String[] ccPeoples,String[] bccPeoples) {
return this.sendMail(subject, toWhos, content, ccPeoples, bccPeoples, null, null);
}
/**
* 通用没有密送附件
* @param subject
* @param toWhos
* @param content
* @param ccPeoples
* @return
*/
public Boolean sendMail(String subject,String[] toWhos,String content,String[] ccPeoples) {
return this.sendMail(subject, toWhos, content, ccPeoples, null, null, null);
}
/**
* 通用没有抄送
* @param subject
* @param toWhos
* @param content
* @return
*/
public Boolean sendMail(String subject,String[] toWhos,String content) {
return this.sendMail(subject, toWhos, content, null, null, null, null);
}
/**
* 发送邮件最基本的方法封装 注意:如果模板中存在了img,multipart必须得有img段
* @param subject 邮件主题
* @param toWhos 接收人员组
* @param content 邮件正文内容
* @param ccPeoples 抄送人员组
* @param bccPeoples 暗送人员组
* @param attachments 附件列表
* @param contentImages 邮件正文图片列表
*/
public Boolean sendMailBaseMethod(String subject,String[] toWhos,String content,String[] ccPeoples,String[] bccPeoples,File[] attachments,File[] contentImages) {
Boolean mailSendResult=false;
// 创建 消息 对象
MimeMessage mimeMessage = mailSender.createMimeMessage();
//在模板多部分对象
// multipart/mixed:附件。
// multipart/related:内嵌资源。
// multipart/alternative:纯文本与超文本共存。
MimeMultipart multipart = new MimeMultipart("mixed");
//正文文字部分加载
BodyPart messageBodyPart = new MimeBodyPart();
try {
// 创建 MimeMessageHelper 对象
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, DEFAULT_ENCODING);;
//不可缺少信息检查
if(subject == null||toWhos == null||toWhos.length == 0||content==null){
logger.error("邮件无法发送,因为缺少基本的参数:邮件主题{}、收件人{}、邮件内容{}",subject,toWhos,content);
throw new RuntimeException("模板邮件无法继续发送,因为缺少必要的参数!");
}
else {
// 设置发件人地址
mimeMessageHelper.setFrom(from);
// 设置收件人地址
mimeMessageHelper.setTo(toWhos);
// 设置主题
mimeMessageHelper.setSubject(subject);
//设置邮件正文内容,判断模板Html还是文本Text
if(!"".equals(content)&&content.indexOf("<!DOCTYPE html>")!=-1&&content.indexOf("<html>")!=-1)
{
//html正文
messageBodyPart.setContent(content, "text/html;charset=UTF-8");
}else {
//text正文
messageBodyPart.setContent(content, "text/plain;charset=UTF-8");
}
multipart.addBodyPart(messageBodyPart);
logger.error("邮件发送,基本的参数:邮件主题{}、收件人{}、邮件内容{}",subject,toWhos,content);
}
//抄送
if(ccPeoples != null)
{
//设置邮件的抄送人:MimeMessageHelper # Assert.notNull(cc, "Cc address array must not be null");
mimeMessageHelper.setCc(ccPeoples);
}
//密送
if(bccPeoples != null)
{
//设置邮件的密送人:MimeMessageHelper # Assert.notNull(bcc, "Bcc address array must not be null");
mimeMessageHelper.setBcc(bccPeoples);
}
//正文内嵌图片处理
if(contentImages!=null&&contentImages.length>0)
{
for(int i=0;i<contentImages.length;i++)
{
if(contentImages[i]!=null)
{
//图片部分加载
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource(contentImages[i]);
messageBodyPart.setDataHandler(new DataHandler(fds));
//模板中<img src="cid:contentImage1"><img src="cid:contentImage2">....
messageBodyPart.setHeader("Content-ID", "<contentImage"+i+">");
multipart.setSubType("related");
//添加图片到多部分对象
multipart.addBodyPart(messageBodyPart);
}
}
}
//合成多部分文件
mimeMessage.setContent(multipart);
//附件处理
if(attachments!=null&&attachments.length>0)
{
for(int i=0;i<attachments.length;i++)
{
if(attachments[i]!=null)
{
messageBodyPart= new MimeBodyPart();
DataHandler dh2 = new DataHandler(new FileDataSource(attachments[i])); // 读取本地文件
messageBodyPart.setDataHandler(dh2); // 将附件数据添加到“节点”
messageBodyPart.setFileName(attachments[i].getName());
multipart.addBodyPart(messageBodyPart);// 设置附件的文件名(需要编码)
}
}
}
// 发送邮件消息
mailSender.send(mimeMessage);
mailSendResult=true;
logger.info("send email successfully...");
} catch (MessagingException e) {
logger.error("send email Fail...");
e.printStackTrace();
}
return mailSendResult;
}
}