<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.sunther.toolbar.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/email")
public class SendEmailController {
@Autowired
private EmailService emailService;
@PostMapping("/send")
public AjaxResult sendEmail(@RequestParam(value = "fromNickName", defaultValue = "") String fromNickName,
String[] sendTo,
String[] ccTo,
String[] bccTo,
String contentStr,
Integer templeteType,
@RequestParam(value = "attachemetList",required = false) List<MultipartFile> attachemetList) throws Exception {
Gson gson = new Gson();
Map<String, String> contentMap = gson.fromJson(contentStr, new TypeToken<Map<String, String>>() {
}.getType());
boolean status = emailService.sendEmail(fromNickName, sendTo, ccTo, bccTo, contentMap, templeteType, attachemetList);
return status ? AjaxResult.success("邮件发送成功") : AjaxResult.error("邮件发送失败");
}
}
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
public interface EmailService {
boolean sendEmail(String fromNickName, String[] sendTo, String[] ccTo, String[] bccTo, Map<String, String> contentMap, Integer templeteType, List<MultipartFile> attachemetList);
}
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.google.gson.Gson;
import com.sunther.toolbar.service.EmailService;
import org.apache.commons.io.IOUtils;
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.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.IOException;
import java.util.*;
@Service
public class EmailServiceImpl implements EmailService {
static Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
@Resource
private JavaMailSender mailSender;
@Value("${spring.mail.fromnickname}")
private String sendFromNickName;
private String sendFrom = "######@163.com";
@Override
public boolean sendEmail(String fromNickName, String[] sendTo, String[] ccTo, String[] bccTo, Map<String, String> contentMap, Integer templeteType, List<MultipartFile> attachemetList) {
return sendEmailCommon(fromNickName, sendTo, ccTo, bccTo, contentMap, templeteType, attachemetList);
}
public boolean sendEmailCommon(String fromNickName, String[] sendTo, String[] ccTo, String[] bccTo, Map<String, String> contentMap, Integer templeteType, List<MultipartFile> files) {
if (StrUtil.isEmpty(fromNickName)) {
fromNickName = sendFromNickName;
}
Gson gson = new Gson();
if (contentMap == null || templeteType == null) {
logger.warn("邮件发送失败:参数错误");
return false;
}
String contentHtml = convertFtlToStr("email.ftl", contentMap);
String subject = "邮箱验证码";
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
boolean continueProcess = handleInfo(helper, sendFrom, sendTo, ccTo, bccTo, subject, contentHtml, true, fromNickName);
if (!continueProcess) {
logger.warn(String.format("邮件基本信息出错,标题:%s", subject));
return false;
}
handleAttachment(helper, subject, files);
ThreadUtil.execAsync(() -> {
mailSender.send(mimeMessage);
});
logger.info(String.format("邮件发送成功!发件人:%s 收件人:%s 标题:%s", sendFrom, Arrays.toString(sendTo), subject));
} catch (Exception e) {
logger.warn(String.format("邮件发送失败!发件人:%s 标题:%s", sendFrom, subject));
logger.warn("邮件内容字段:" + gson.toJson(contentHtml));
logger.warn("",e);
return false;
}
return true;
}
public static String convertFtlToStr(String ftlTemplate, Map<String, String> dataModel) {
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
Template template = engine.getTemplate(ftlTemplate);
String content = template.render(dataModel);
return content;
}
private boolean handleInfo(MimeMessageHelper helper, String sendFrom, String[] sendPeoples, String[] ccPeoples,
String[] bccPeoples, String subject, String content, boolean isHtml, String fromNickName) {
try {
helper.setFrom(fromNickName + "<" + sendFrom + ">");
helper.setTo(sendPeoples);
helper.setSubject(subject);
helper.setText(content, isHtml);
if (ccPeoples != null && ccPeoples.length > 0) {
helper.setCc(ccPeoples);
}
if (bccPeoples != null && bccPeoples.length > 0) {
helper.setBcc(bccPeoples);
}
return true;
} catch (MessagingException e) {
e.printStackTrace();
logger.warn("邮件基本信息出错:" + subject,e);
}
return false;
}
private void handleAttachment(MimeMessageHelper helper, String subject, List<MultipartFile> multipartFiles) throws IOException {
if (multipartFiles !=null && multipartFiles.size() > 0){
for (MultipartFile multipartFile : multipartFiles) {
try {
String filename = multipartFile.getOriginalFilename();
if (!StrUtil.isEmpty(filename)){
helper.addAttachment(MimeUtility.encodeWord(filename), new ByteArrayResource(IOUtils.toByteArray(multipartFile.getInputStream())));
}
} catch (MessagingException e) {
logger.warn(String.format("邮件添加附件异常!邮件主题:%s 附件名称:%s", subject, multipartFile.getName()), e);
}
}
}
}
}
- ftl
(src/main/resources/template/email.ftl)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<style>
@page {
margin: 0;
}
</style>
</head>
<body style="margin: 0px;
padding: 0px;
font: 100% SimSun, Microsoft YaHei, Times New Roman, Verdana, Arial, Helvetica, sans-serif;
color: #000;">
<div style="height: auto;
width: 820px;
min-width: 820px;
margin: 0 auto;
margin-top: 20px;
border: 1px solid #eee;">
<div style="padding: 10px;padding-bottom: 0px;">
<p style="margin-bottom: 10px;padding-bottom: 0px;">尊敬的用户,您好:</p>
<p style="text-indent: 2em; margin-bottom: 10px;">您正在申请邮箱验证,您的验证码为:</p>
<p style="text-align: center;
font-family: Times New Roman;
font-size: 22px;
color: #C60024;
padding: 20px 0px;
margin-bottom: 10px;
font-weight: bold;
background: #ebebeb;">${code}</p>
<div class="foot-hr hr" style="margin: 0 auto;
z-index: 111;
width: 800px;
margin-top: 30px;
border-top: 1px solid #DA251D;">
</div>
<div style="text-align: center;
font-size: 12px;
padding: 20px 0px;
font-family: Microsoft YaHei;">
Copyright ©${.now?string("yyyy")} <a hover="color: #DA251D;" style="color: #999;" href="https://github.com/elunez/eladmin" target="_blank">ELADMIN</a> 后台管理系统 All Rights Reserved.
</div>
</div>
</div>
</body>
</html>
spring:
mail:
host: smtp.163.com
username: username
password: password
default-encoding: UTF-8
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
fromnickname: "伍六七"