java 发送邮件嵌套HTML模板 (二)

我们平时发送邮件基本都是以纯文本的形式,达到通知的目的就可以了,如果要给我们的客户发纯文本邮件未免显得太low,用户体验性很不好,那怎么解决这个问题呢?

so easy   我们的html模板邮件来了 。

只要html css功底到位,那发出去的邮件都可以有一个质的提升:

横看成岭侧成峰 ,远近高低各不同

废话少说,小试牛刀:

1、首先要准备好一个html模板, 

     这里简单写了个学校录取名单的模板

     student.html 代码如下:




	
	
	



年录取名单
姓名 年龄 性别 准考证号 成绩 排名

此致

莘县一中
欢迎第47届新同学入学

 

 

2、默认maven项目: 

      pom.xml 添加依赖



    org.springframework.boot
    spring-boot-starter-thymeleaf


    org.springframework.boot
    spring-boot-starter-mail

3、application.properties 配置文件如下

# SMTP 地址
spring.mail.host=smtp.163.com
# 发件人邮箱地址
[email protected]
# 邮箱密码(授权码)
spring.mail.password=XXXXXXXX
# 编码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=false
spring.mail.properties.mail.smtp.starttls.required=false
# 模板路径 resources文件夹下的路径
spring.thymeleaf.prefix=classpath:/templates/
# 模板类型
spring.thymeleaf.servlet.content-type: text/html
# 是否缓存
spring.thymeleaf.cache: false
# HTML 模板
spring.thymeleaf.mode: HTML5
spring.thymeleaf.check-template-location=true

4、java 代码如下:

package com.weryou.email.kit;

import java.util.Map;

/**
 * @ClassName MailKit
 * @Description
 * @Author weryou
 * @Date 2021/7/19 22:38
 * @Version 1.0
 **/
public class MailKit {

    //标题
    private String title;
    //内容
    private String content;
    //接收人邮件地址
    private String email;
    //附加,value 文件的绝对地址/动态模板数据
    private Map attachment;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Map getAttachment() {
        return attachment;
    }

    public void setAttachment(Map attachment) {
        this.attachment = attachment;
    }

}
package com.weryou.email.model;

/**
 * @ClassName StudentVo
 * @Description
 * @Author weryou
 * @Date 2021/7/17 22:27
 * @Version 1.0
 **/
public class StudentVo {

    private String name;
    private String sex;
    private int age;
    private String card;
    private int score;
    private int order;



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getCard() {
        return card;
    }

    public void setCard(String card) {
        this.card = card;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }
}

package com.weryou.email.service;

import com.weryou.email.kit.MailKit;
import com.weryou.email.model.StudentVo;
import java.util.List;

public interface SendEmailService {

    /**
     * 发送邮件
     * @param mailKit
     * @param modelName
     * @param emailType
     * @return
     */
    boolean sendTemplateMail(MailKit mailKit, String modelName, String emailType);


    /**
     * 获取学生信息
     * @return
     */
    List  getStudentInfo();


}

package com.weryou.email.service.impl;

import com.weryou.email.kit.MailKit;
import com.weryou.email.model.StudentVo;
import com.weryou.email.service.SendEmailService;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SendEmailServiceImpl
 * @Description
 * @Author weryou
 * @Date 2021/7/19 21:48
 * @Version 1.0
 **/
@Service
public class SendEmailServiceImpl implements SendEmailService {

    private final static Logger log = LoggerFactory.getLogger(SendEmailServiceImpl.class);

    private final static String SEX_1 = "1";//男生
    private final static String SEX_2 = "2";//女生


    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;



    /**
     * thymeleaf模板
     * @param emailType
     */
    @Async
    @Override
    public boolean sendTemplateMail(MailKit mailKit, String modelName, String emailType) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 昵称
            String nickname = "ShenXian NO.1 School";
            // From: 发件人
            mimeMessage.setFrom(new InternetAddress(from, nickname, "UTF-8"));
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            //messageHelper.setFrom(from);// 发送人的邮箱
            if(mailKit.getEmail().contains(",")){
                String[] emails = mailKit.getEmail().split(",");
                int s = 1;
                for (String email:emails){
                    if(s==1){
                        //第一个收件人用setTo
                        messageHelper.setTo(email);
                    }else{
                        //多个收件人用addTo
                        messageHelper.addTo(email);
                    }
                    s++;
                }
            }else{
                messageHelper.setTo(mailKit.getEmail());
            }
            //标题
            messageHelper.setSubject(mailKit.getTitle());
            //使用模板thymeleaf
            Context context = new Context();
            //定义模板数据
            context.setVariables(mailKit.getAttachment());
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process(modelName,context);
            messageHelper.setText(emailContent,true);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("模板邮件发送失败->message:{}",e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public List getStudentInfo() {
        List lists = new ArrayList();
        StudentVo vo1 = new StudentVo();
        vo1.setAge(14);
        vo1.setCard("20210001");
        vo1.setName("赵小明");
        vo1.setScore(686);
        vo1.setOrder(1);
        vo1.setSex(SendEmailServiceImpl.SEX_1);
        lists.add(vo1);

        StudentVo vo2 = new StudentVo();
        vo2.setAge(15);
        vo2.setCard("20210002");
        vo2.setName("王小花");
        vo2.setScore(677);
        vo2.setOrder(2);
        vo2.setSex(SendEmailServiceImpl.SEX_2);
        lists.add(vo2);


        StudentVo vo3 = new StudentVo();
        vo3.setAge(14);
        vo3.setCard("20210003");
        vo3.setName("张丽丽");
        vo3.setScore(675);
        vo3.setOrder(3);
        vo3.setSex(SendEmailServiceImpl.SEX_2);
        lists.add(vo3);
        return  lists;
    }


}
package com.weryou.email.controller;

import com.weryou.email.kit.MailKit;
import com.weryou.email.model.StudentVo;
import com.weryou.email.service.SendEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName SendEmailCtrl
 * @Description
 * @Author weryou
 * @Date 2021/7/19 20:09
 * @Version 1.0
 **/

@RestController
@RequestMapping("/email")
@Validated
public class SendEmailCtrl {

    private final static Logger log = LoggerFactory.getLogger(SendEmailCtrl.class);

    @Autowired
    private SendEmailService sendEmailService;


    /**
     * 发送邮件
     * @return
     */
    @GetMapping("/templateMail")
    @ResponseBody
    public String templateMail() {
        List voList = sendEmailService.getStudentInfo();

        MailKit mailKit = new MailKit();
        mailKit.setTitle("录取名单");
        mailKit.setContent("莘县一中录取学生名单");
        String emailAddr = "[email protected]";
        mailKit.setEmail(emailAddr);
        try {
            Map map = new HashMap<>();
            map.put("username","All");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            log.info("录取名单邮件发送时间:"+df.format(new Date()));
            map.put("year",df.format(new Date()).toString().substring(0,4));
            map.put("datalist",voList);
            mailKit.setAttachment(map);
            boolean flag = sendEmailService.sendTemplateMail(mailKit,"student","SCHOOL");
            if(flag){
                log.info("邮件发送成功!");
            }else{
                log.warn("邮件发送失败!");
            }
        } catch (Exception e) {
            log.error("邮件发送异常:",e);
            return "发送失败";
        }
        return "发送成功";
    }


}

5、代码目录结构:

java 发送邮件嵌套HTML模板 (二)_第1张图片

6、把邮件地址替换成真实的地址,启动服务见证奇迹吧

7、http://localhost:8080/email/templateMail

效果图:

java 发送邮件嵌套HTML模板 (二)_第2张图片

 

                                                        End  2021年7月19日23:02:56

你可能感兴趣的:(email,java)