记录 java 发送邮箱 读取 ftl 模板

18 篇文章 1 订阅
  • maven
<!-- 邮件发送 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
  • controller
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;

/**
 * @author csb
 * @description: TODO
 * @date 2023/11/30 11:38
 */
@RestController
@RequestMapping("/email")
public class SendEmailController {

    @Autowired
    private EmailService emailService;

    /**
     * 邮件发送
     *
     * @param sendTo         接受人
     * @param ccTo           抄送人
     * @param bccTo          秘密抄送人
     * @param contentStr     contentMap,json化
     * @param templeteType   模板类型
     * @param attachemetList 附件
     * @return
     */
    @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("邮件发送失败");
    }

}
  • service
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);
}
  • impl
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.*;

/**
 * @author csb
 * @description: TODO
 * @date 2023/11/30 11:39
 */
@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);
    }

    /**
     * 邮件发送
     *
     * @param sendTo         接受人
     * @param ccTo           抄送人
     * @param bccTo          秘密抄送人
     * @param contentMap     填充模板数据map
     * @param templeteType   模板类型
     * @param files 附件
     * @return
     */
    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;
    }

    /**
     * 邮件基本信息处理
     *
     * @param helper      邮件包装类
     * @param sendFrom    发送人
     * @param sendPeoples 收件人
     * @param ccPeoples   抄送人
     * @param bccPeoples  秘密抄送人
     * @param subject     主题
     * @param content     邮件内容
     * @param isHtml      是否是HTML文件,用于区分带附件的简单文本邮件和真正的HTML文件
     * @return 是否异常
     */
    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;
    }

    /**
     * 邮件添加附件
     *
     * @param helper         邮件包装类
     * @param subject        主题
     * @param multipartFiles 附件列表
     */
    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 &copy;${.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>

  • yml 邮箱配置
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: "伍六七"
  • 测试验证

postman参数

  • 效果

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值