spring boot2.x发送邮件

Posted NetWhite

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot2.x发送邮件相关的知识,希望对你有一定的参考价值。

1.引入依赖

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

示例spring boot工程为2.2.3.RELEASE版本

2.配置

application.yml里配置邮箱主机地址和用户名密码:

spring:
  mail:
    host: smtp.163.net
    username: xxx@163.com
    password: PASS

3.示例代码

@Component
public class MailClient {

    @Autowired
    private JavaMailSender mailSender;


    /**
     * 普通邮件发送
     *
     * @param from    发件人邮箱
     * @param to      收件人邮箱
     * @param subject 邮箱主题
     * @param content 邮箱正文
     */
    public void send(String from, String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    /**
     * 发送附件
     *
     * @param from       发件人邮箱
     * @param to         收件人邮箱
     * @param subject    邮箱主题
     * @param content    邮箱正文
     * @param name2paths 附件名及文件路径
     * @throws MessagingException 记得处理异常
     */
    public void sendWithAttachment(String from, String to, String subject, String content,
        Map<String, String> name2paths) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content);
        for (Map.Entry<String, String> entry : name2paths.entrySet()) {
            helper.addAttachment(entry.getKey(), new FileSystemResource(entry.getValue()));
        }
        mailSender.send(mimeMessage);
    }

}

示例中,两个方法,一个发送普通邮件,一个发送带附件。

4.测试

@SpringBootApplication
public class EmailApplication implements CommandLineRunner {

    @Autowired
    private MailClient mailClient;

    public static void main(String[] args) {
        SpringApplication.run(EmailApplication.class, args);
    }

    @Override public void run(String... args) throws Exception {
        mailClient.send("xxx@163.com", "target@163.m", "测试", "Hello, World");

        Map<String, String> attachment = new HashMap<>();
        attachment.put("logback-spring.xml", "/Users/xuxd/DemoCode/java/app.demo/app.demo-web/src/main/resources/logback-spring.xml");
        mailClient.sendWithAttachment("xxx@163.com", "target@163.m",  "测试", "Hello, World", attachment);    
    }

}

5.发送html格式的邮件

邮件内容需要美化,比如表格类,需要发送html格式的邮件。需要引入thymleaf,spring2.x和1.x用的template不一样,2.x是thymeleaf,如下是2.x示例:

1.增加template依赖

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

2.在classpath:resources/templates下增加html模板,如下:

下面是user.html的代码,里面包含了if-else和for循环的示例用法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Info</title>

    <style>
        /** Table 表格样式 **/
        table {
            border-collapse: collapse;
            width: 80%;
            border: 1px solid #c6c6c6 !important;
            margin-bottom: 20px;
        }

        table thead tr td {
            background-color: lightblue;
        }

        table th {
            border-collapse: collapse;
            border-right: 1px solid #c6c6c6 !important;
            border-bottom: 1px solid #c6c6c6 !important;
            background-color: #ddeeff !important;
            padding: 5px 9px;
            font-size: 14px;
            font-weight: normal;
            text-align: center;
        }

        table td {
            border-collapse: collapse;
            border-right: 1px solid #c6c6c6 !important;
            border-bottom: 1px solid #c6c6c6 !important;
            padding: 5px 9px;
            font-size: 12px;
            font-weight: normal;
            text-align: center;
            word-break: break-all;
        }

        table tr:nth-child(odd) {
            background-color: #fff !important;
        }

        table tr:nth-child(even) {
            background-color: #f8f8f8 !important;
        }
    </style>
</head>
<body>

<!--如果都是男孩-->
<div th:if="${isBoys}">
    <h1><span th:text="${welcome}"></span>男孩们</h1>

    <div th:if="${not #lists.isEmpty(people)}">
        <h2>详细信息</h2>
        <table>
            <thead>
            <tr>
                <th>用户名</th>
                <th>年龄</th>
            </tr>
            </thead>
            <tbody>
            <!--    循环遍历信息-->
            <tr th:each="p:${people}">
                <td th:text="${p.name}"></td>
                <td th:text="${p.age}"></td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
<!--否则都是女孩-->
<div th:unless="${isBoys}">
    <h1><span th:text="${welcome}"></span>女孩们</h1>
    <div th:if="${not #lists.isEmpty(people)}">
        <h2>详细信息</h2>
        <table>
            <thead>
            <tr>
                <th>用户名</th>
                <th>年龄</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="p:${people}">
                <td th:text="${p.name}"></td>
                <td th:text="${p.age}"></td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>

3.邮件发送客户端代码:

@Component
public class MailClient {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送html模板的邮件,需要用
     */
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * html模板的邮件
     *
     * @param from     发件人邮箱
     * @param to       收件人邮箱
     * @param subject  邮箱主题
     * @param template 邮件模板
     * @param vars     邮件模板中的变量参数
     * @throws MessagingException 记得处理异常
     */
    public void sendHtml(String from, String to, String subject, String template,
        Map<String, Object> vars) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);

        Context context = new Context();
        context.setVariables(vars);
        String content = templateEngine.process(template, context);

        helper.setText(content, true);

        mailSender.send(mimeMessage);
    }

}

4.发送示例


@SpringBootApplication
public class EmailApplication implements CommandLineRunner {

    @Autowired
    private MailClient mailClient;

    public static void main(String[] args) {
        SpringApplication.run(EmailApplication.class, args);
    }

    @Override public void run(String... args) throws Exception {

        List<User> users = new ArrayList<>();
        users.add(new User("小明", 8));
        users.add(new User("小王", 18));
        Map<String, Object> body = new HashMap<>();
        body.put("people", users);
        body.put("welcome", "欢迎");
        body.put("isBoys", true);
        // "user"就是前面templates下的user.html模板
        mailClient.sendHtml("xxx@163.com", "target@163.com", "测试", "user", body);
    }

    class User {
        public String name;
        public int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

    }
}

body里的值是模板需要的变量的值

以上是关于spring boot2.x发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

spring boot2.x和activiti如何配置

Spring Boot2.X中findOne的用法

Spring Boot2.x 的Druid连接池配置[附带监控]

Spring Boot2.x + Quartz 定时任务模块

我应该如何使用 Outlook 发送代码片段?

spring cloudspring boot2.x下 使用feign,注解@EnableFeignClients 找不到的解决方法