Spring Boot + JavaMailSender + Thymeleaf implement server to send mail

Spring Boot- achieve mailing


What- What is mail service

In the early Internet mail service it has emerged, and now the Internet has become an essential service life. So how is the mail service work? A typical process is given below of message transmission and reception:
1, the sender using the SMTP protocol to transfer messages to the mail server A;
2, A mail server according to the specified recipient message, the message delivery to the corresponding mail server B;
. 3 , the recipient uses the POP3 protocol to receive mail from a mail server B.
SMTP (Simple Mail Transfer Protocol) is the Internet standard mail (email) transmission, as defined in RFC5321, use the default port 25;
POP3 (Post Office Protocol - Version 3) is mainly used to support the use of electronic client remote management on the server mail. Defined in RFC 1939, for the third edition of the POP protocol (latest edition).
These two protocols are application layer protocol TCP / IP protocol suite, it runs over the TCP layer.
We use the daily mail clients, Web Mail are behind in the running of these two agreements, the completion of the process of sending and receiving mail. And now we need to use the SMTP protocol to transmit messages to be sent to the user's mail server.
Transfer messages from the client to the server requires cooperation of both sides, and the rules defined in the SMTP protocol. We now need to do is find a SMTP server, and then implement an SMTP client, and then let the client sends a message to the server.


Why- why the system is to establish a mail service

E-mail all over the world have a common protocol. So you can use any e-mail client in any way to check your mail. E-mail client on the end of the world less than 1000 kinds, all of them in different ways to meet the different needs of the population, the message has the following characteristics:
① communication within the enterprise, or the mail service is considered "official" than instant messaging "reliable".
② support forwarding / cc, open, unified communications protocol, can be archived.


Why- how to achieve mail service

  • Configure the mail server

Open SMTP server, set the authorization code, the subsequent write code need to change the authorization code, coding passwords in non-mail password but the authorization code, such as: set the authorization code is: 123456


  • Realization mail client

① Gradle added Spring Mail dependence

compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'

② modify application.properties, add mailbox configuration

##################################---Spring Mail发送邮件---##############################################
# JavaMailSender 邮件发送的配置
spring.mail.default-encoding=UTF-8 
spring.mail.host=smtp.163.com
spring.mail.port=465
[email protected]
# 邮箱开启的授权码
spring.mail.password=123456
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=true
spring.mail.properties.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true

  • Send e-mail tools JavaMailUtil write code that supports sending plain text messages, html email, email attachments, thymeleaf template message types.
package com.javalsj.blog.mail;

import java.io.File;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.javalsj.blog.common.FileUtil;

/**
 * @description 发送邮件工具,支持发送纯文本邮件、html邮件、附件邮件、thymeleaf模板邮件类型。
 * @author WANGJIHONG
 * @date 2018年3月14日 下午10:17:40
 * @Copyright 版权所有 (c) www.javalsj.com
 * @memo 无备注说明
 */
@Component
public class JavaMailUtil {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Java邮件发送器
     */
    @Autowired
    private JavaMailSender mailSender;

    /**
     * thymeleaf模板引擎
     */
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送不含附件,且不含嵌入html静态资源页面的纯文本简单邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receiver
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopy
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。
     */
    public void sendSimpleEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text)
            throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, false, null);
    }

    /**
     * 发送含嵌入html静态资源页面, 但不含附件的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如: <html><body>
     *            <h1>213123</h1></body></html>
     */
    public void sendHtmlEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text)
            throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
    }

    /**
     * 发送含附件,但不含嵌入html静态资源页面的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。
     * @param attachmentFilePaths
     *            附件文件路径 如:http://www.javalsj.com/resource/test.jpg,
     *            http://www.javalsj.com/resource/test2.jpg
     */
    public void sendAttachmentsEmail(String deliver, String[] receivers, String[] carbonCopys, String subject,
            String text, String[] attachmentFilePaths) throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, false, attachmentFilePaths);
    }

    /**
     * 发送含附件,且含嵌入html静态资源页面的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            <html><body><img src=\"cid:test\"><img
     *            src=\"cid:test2\"></body></html>
     * @param attachmentFilePaths
     *            附件文件路径 如:http://www.javalsj.com/resource/test.jpg,
     *            http://www.javalsj.com/resource/test2.jpg
     *            需要注意的是addInline函数中资源名称attchmentFileName需要与正文中cid:attchmentFileName对应起来
     */
    public void sendHtmlAndAttachmentsEmail(String deliver, String[] receivers, String[] carbonCopys, String subject,
            String text, String[] attachmentFilePaths) throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, attachmentFilePaths);
    }

    /**
     * 发送thymeleaf模板邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param thymeleafTemplatePath
     *            邮件模板 如:mail\mailTemplate.html。
     * @param thymeleafTemplateVariable
     *            邮件模板变量集 
     */
    public void sendTemplateEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String thymeleafTemplatePath,
            Map<String, Object> thymeleafTemplateVariable) throws Exception {
        String text = null;
        if (thymeleafTemplateVariable != null && thymeleafTemplateVariable.size() > 0) {
            Context context = new Context();
            thymeleafTemplateVariable.forEach((key, value)->context.setVariable(key, value));
            text = templateEngine.process(thymeleafTemplatePath, context);
        }
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
    }

    /**
     * 发送的邮件(支持带附件/html类型的邮件)
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。 <html><body><img
     *            src=\"cid:attchmentFileName\"></body></html>
     * @param attachmentFilePaths
     *            附件文件路径 如:
     *            需要注意的是addInline函数中资源名称attchmentFileName需要与正文中cid:attchmentFileName对应起来
     * @throws Exception
     *             邮件发送过程中的异常信息
     */
    private void sendMimeMail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text,
            boolean isHtml, String[] attachmentFilePaths) throws Exception {
        StopWatch stopWatch = new StopWatch();
        try {
            stopWatch.start();
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(deliver);
            helper.setTo(receivers);
            helper.setCc(carbonCopys);
            helper.setSubject(subject);
            helper.setText(text, isHtml);
            // 添加邮件附件
            if (attachmentFilePaths != null && attachmentFilePaths.length > 0) {
                for (String attachmentFilePath : attachmentFilePaths) {
                    File file = new File(attachmentFilePath);
                    if (file.exists()) {
                        String attachmentFile = attachmentFilePath
                                .substring(attachmentFilePath.lastIndexOf(File.separator));
                        long size = FileUtil.getDirSize(file);
                        if (size > 1024 * 1024) {
                            String msg = String.format("邮件单个附件大小不允许超过1MB,[%s]文件大小[%s]。", attachmentFilePath,
                                    FileUtil.formatSize(size));
                            throw new RuntimeException(msg);
                        } else {
                            FileSystemResource fileSystemResource = new FileSystemResource(file);
                            helper.addInline(attachmentFile, fileSystemResource);
                        }
                    }
                }
            }
            mailSender.send(mimeMessage);
            stopWatch.stop();
            logger.info("邮件发送成功, 花费时间{}秒", stopWatch.getTotalTimeSeconds());
        } catch (Exception e) {
            logger.error("邮件发送失败, 失败原因 :{} 。", e.getMessage(), e);
            throw e;
        }
    }

}

  • Write simple text messages sent Controller
@RequestMapping(value = "/sendSimpleEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result sendSimpleEmail() {
        Result result;
        try {
            javaMailUtil.sendSimpleEmail("[email protected]", new String[] { "[email protected]", "[email protected]" },
                    new String[] { "[email protected]" }, "您收到一封高大上的邮件,请查收。", "测试邮件逗你玩的。");
            result = ResultFactory.buildSuccessResult(null);
        } catch (Exception e) {
            result = ResultFactory.buildFailResult(e.getMessage());
        }
        return result;
    }

 


  • Send e-mail template engine written page

mailTemplate.html page code:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件模板</title>
</head>
<body>
    <div>
        用户名:<input th:text="${username}"/> <br /> 
        密码: <input th:text="${password}"/>
    </div>
</body>
</html>

Controller test code:

@RequestMapping(value = "/sendTemplateEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result sendTemplateEmail() {
        Result result = null;
        try {
            String thymeleafTemplatePath = "mail/mailTemplate";
            Map<String, Object> thymeleafTemplateVariable = new HashMap<String, Object>();
            thymeleafTemplateVariable.put("username", "javalsj");
            thymeleafTemplateVariable.put("password", "123456");
            javaMailUtil.sendTemplateEmail("[email protected]", 
                    new String[] { "[email protected]", "[email protected]" },
                    new String[] { "[email protected]" }, 
                    "您收到一封高大上的邮件,请查收。",
                    thymeleafTemplatePath,
                    thymeleafTemplateVariable);
            result = ResultFactory.buildSuccessResult(null);
        } catch (Exception e) {
            result = ResultFactory.buildFailResult(e.getMessage());
        }
        return result;
    }

 


to sum up

As used herein, Spring Boot + JavaMailSender + Thymeleaf implements the server to send plain text messages, html e-mail, e-mail attachments and e-mail Thymeleaf template function, due to the Spring Boot default template engine is Thymeleaf, so use the default automatic configuration Thymeleaf can, without making this article Thymeleaf configuration alone.

Guess you like

Origin blog.csdn.net/ryuenkyo/article/details/91379115