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里的值是模板需要的变量的值

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不识君的荒漠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值