SpringBoot 使用JavaMailSender发送邮件2

原创
2020/12/10 23:33
阅读数 555

为了更容易更规范维护邮件内容,我们推荐使用模板引擎技术。常用的模板引擎有这几种Thymeleaf、FreeMarker、Velocity等。我们在这里就使用前面两种来实现发送邮件。

 

一、使用Thymeleaf模板技术发送邮件

Thymeleaf是SpringBoot推荐的官方模板引擎技术,使用非常的简单方便。

(1)添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

(2)编写实现代码

编写发送邮件接口。

import com.example.demo.entity.Member;
import com.example.demo.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Arrays;
import java.util.List;

@RestController
public class MailController {

    private final static String FROM_MAIL = "2333@163.com";
    private final static String TO_MAIL = "123@qq.com";

    @Autowired
    MailService mailService;

    @Autowired
    TemplateEngine templateEngine;

    @GetMapping("/sendTemplate")
    public String sendTemplate(){
        //渲染模版
        Member member1 = new Member().setName("张飞").setSex("男").setEmail("123@qq.com");
        Member member2 = new Member().setName("孙尚香").setSex("女").setEmail("222@qq.com");
        Member member3 = new Member().setName("曹操").setSex("男").setEmail("666@qq.com");
        List<Member> memberList = Arrays.asList(member1, member2, member3);

        //通过Context构造模版中变量需要的值
        Context ctx = new Context();
        ctx.setVariable("memberList", memberList);
        //使用TemplateEngine对模版进行渲染
        String mail = templateEngine.process("mail.html", ctx);
        //发送邮箱
        mailService.sendTemplate(FROM_MAIL, TO_MAIL, "邮件的标题", mail);

        return "发送成功";
    }

}

编写发送邮件服务 

public interface MailService {

    void sendTemplate(String from, String to, String subject, String content);

}
import com.example.demo.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    JavaMailSender javaMailSender;

    /**
     * 发送html模板邮件
     * @param from 邮件发送者
     * @param to 收件人
     * @param subject 邮件主题
     * @param content html格式的邮件内容
     */
    @Override
    public void sendTemplate(String from, String to, String subject, String content) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setText(content, true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            System.out.println("发送失败");
        }
    }
}

编写测试数据实体 

import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class Member {

    private String name;

    private String sex;

    private String email;

}

(3)创建邮件模板

Thymeleaf模版默认位置是resources/templates,我们在该目录下创建一个邮件模版 mail.html。

代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>邮件模板</title>
    <style type="text/css">
        ul li {
            list-style: none;
            height: 35px;
            line-height:35px;
        }
    </style>
</head>
<body>
    <div>
        <h3>会员信息</h3>
        <ul>
            <li th:each="member: ${memberList}">
                姓名:[[${member.name}]]&nbsp;&nbsp;
                性别:[[${member.sex}]]&nbsp;&nbsp;
                邮箱:[[${member.email}]]
            </li>
        </ul>
    </div>
</body>
</html>

(4)验证结果

访问接口:http://127.0.0.1:8082/sendTemplate

 

二、使用FreeMarker模板技术发送邮件

(1)添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

(2)编写实现代码

编写发送邮件接口。

import com.example.demo.TestApplication;
import com.example.demo.entity.Member;
import com.example.demo.service.MailService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MailController {

    private final static String FROM_MAIL = "2333@163.com";
    private final static String TO_MAIL = "123@qq.com";

    @Autowired
    MailService mailService;
    
    @GetMapping("/sendTemplate")
    public String sendTemplate(){
        try {
            //配置FreeMarker模版位置
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            ClassLoader loader = TestApplication.class.getClassLoader();
            configuration.setClassLoaderForTemplateLoading(loader,"ftl");
            //配置模版文件
            Template template = configuration.getTemplate("mail.ftl");

            //渲染模版
            StringWriter mail = new StringWriter();
            Member member1 = new Member().setName("张飞").setSex("男").setEmail("123@qq.com");
            Member member2 = new Member().setName("孙尚香").setSex("女").setEmail("222@qq.com");
            Member member3 = new Member().setName("曹操").setSex("男").setEmail("666@qq.com");
            List<Member> memberList = Arrays.asList(member1, member2, member3);
            Map<String, Object> map = new HashMap();
            map.put("memberList", memberList);
            template.process(map, mail);

            //发送邮箱
            mailService.sendTemplate(FROM_MAIL, TO_MAIL, "邮件的标题", mail.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "发送成功";
    }

邮件服务和上面的一样,我们这边就不过多描述了。

public interface MailService {

    void sendTemplate(String from, String to, String subject, String content);

}
import com.example.demo.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    JavaMailSender javaMailSender;

    /**
     * 发送html模板邮件
     * @param from 邮件发送者
     * @param to 收件人
     * @param subject 邮件主题
     * @param content html格式的邮件内容
     */
    @Override
    public void sendTemplate(String from, String to, String subject, String content) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setText(content, true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            System.out.println("发送失败");
        }
    }
}
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class Member {

    private String name;

    private String sex;

    private String email;

}

(3)创建邮件模板

这里我们resources目录下面创建了一个ftl的文件,在该目录创建了一个mail.ftl文件。

代码如下:

<style type="text/css">
    ul li {
        list-style: none;
        height: 35px;
        line-height:35px;
    }
</style>
<div>
    <h3>会员信息</h3>
    <ul>
        <#list memberList as member>
            <li>姓名:${member.name}&nbsp;&nbsp;性别:${member.sex}&nbsp;&nbsp;邮箱:${member.email}</li>
        </#list>
    </ul>
</div>

(4)验证结果

访问接口:http://127.0.0.1:8082/sendTemplate

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部