Spring boot series integrated mail sending service and several ways of mail sending

Posted by jpbellavance on Sat, 09 May 2020 05:43:17 +0200

Previous recommendation

Spring boot series (I) idea new spring boot project

Introduction to SpringBoot series (2)

Spring boot series (3) configuration file details

Spring boot series (IV) detailed explanation of web static resource configuration

Spring boot series (V) Mybatis integrated full detailed version

Spring boot series (6) integrated tymeleaf detailed Edition

Spring boot series (7) integration interface document swagger, use, test

Spring boot series (8) minutes learn spring boot's multiple cross domain solutions

Spring boot series (9) correct posture for single and multi file upload

Spring boot series (10) elegant handling of unified exception handling and unified result return

How much do you know about the configuration and use of spring boot series (XI) interceptors and interceptor chains?

Spring boot series (12) filter configuration details

Spring boot series (XIII) unified log processing, logback+slf4j AOP + custom annotation, go!


1, Introduction to SMTP protocol

  SMTP is a protocol that provides reliable and effective e-mail transmission. SMTP is a kind of mail service based on FTP file transfer service, which is mainly used for mail information transmission between systems and provides notifications about letters. SMTP is independent of specific transmission subsystem and only needs reliable and orderly data flow channel support. One of the important characteristics of SMTP is that it can transmit mail across the network, that is, "SMTP mail relay". With SMTP, mail transmission between the same network processing processes can be realized, and mail transmission between a processing process and other networks can also be realized through a repeater or gateway.

  simply put: we use these mail sending functions. There is a special e-mail server between them, similar to the post office. You send the mail to the post office, and the post office will send it to the corresponding post office according to your mailing address, and then the receiver will go to the post office to get the mail. E-mail server is a post office between the Internet. Different networks can also send e-mail.

  Spring framework is encapsulated on the basis of java e-mail service, and Spring boot further encapsulates e e-mail service on the basis of Spring, making it more convenient and flexible for Spring boot to send e-mail.

2, Open SMTP service and get authorization code

  here we take QQ mailbox as an example. To send QQ mail in spring boot, you must first turn on the SMTP function of QQ mailbox, which is turned off by default. The specific operations are as follows. Enter email → settings → account, and then find the following:

  the first one will be opened. I have already opened it here, so I don't need to open it again. As for the POP3 protocol, This is a protocol to read mail from the mail server. Through POP3 protocol, the addressee does not need to participate in the mail reading process with the mail server, simplifying the user's operation. The addressee can process the mail "offline" and receive and read the mail easily.

  then we need to obtain an authorization code after opening it, which we need to use to write mail configuration later. Getting authorization code may require authentication or something. Save the authorization code.

3, Dependency import and configuration description

  dependent import:


  to facilitate testing, we also need to import the dependency of starter web.


    host: smtp.qq.com
    username: qzstudynote@qq.com
    password: zxcvbnmkj
            class: javax.net.ssl.SSLSocketFactory
##         ssl:
##           enable :true
    default-encoding: utf-8

  Configuration Description:

  • host is your email server address,
  • username is your email account with suffix
  • password is the authorization code you just copied. I'm scribbling here;
  • Default encoding sets the message code to utf-8;
  • properties: additional configuration. Here I write two. Only one of them is enough. Enable ssl encryption to ensure a secure connection.

4, Mail sending

1. Simple email

Write controller, or add test directly to test module

public class MailController {
    JavaMailSenderImpl javaMailSender;
    public String sendMail(){
        SimpleMailMessage message = new SimpleMailMessage();
        //Mail Settings
        message.setSubject("Message subject");
        message.setText("Message content");
        return "Simple email sent successfully!"

Code Description: JavaMailSenderImpl is an implementation class used to send mail in spring boot. We need to inject it into bean s for use. There are some methods in it, only a few are shown here, and others are very simple, such as sending date, CC person, etc. Multiple receivers can be set, as above.

2. Email with attachments and text with pictures##

public String sendMineMail() throws MessagingException {
     //1. Create a complex message
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //Message subject
        helper.setSubject("This is an email");
        //Add picture to text
        helper.addInline("image1",new FileSystemResource("D:\\images\\spring\\1.jpg"));
        //Message content
        helper.setText("Full stack learning notes<a href='https://Www.cnblogs.com/swzx-1213 / ', baidu click < / a > < img SRC ='cid: image1' > img > ", true);
        //Attachment add picture
        helper.addAttachment("1.jpg",new File("D:\\images\\spring\\1.jpg"));
        //Attachment add word document
        helper.addAttachment("Ha ha ha.docx",new File("D:\\images\\spring\\Ha ha ha.docx"));

       return "Complex email sending!";

  code Description:

  • Create a MimeMessage message, but we also need to create a tool class MimeMessageHelper, which is equivalent to a proxy class. The property configuration of the message is implemented by this tool class.
  • addInline(), the first parameter is a contentId,String type, which is equivalent to a key. The second parameter is a Resource object, Resource object. Here we pass a FileSystemResource object for local pictures. Of course, this is the parameter of the addInline method we use. There are other parameter types, so-called overloads.
  • setText(), the first parameter used here is the text string, and the second is whether to parse the html syntax in the text.
  • addAttachment() is used to add attachments. Attachments are different from the pictures we added before. Attachments are not downloaded files, while resource files are directly displayed in the body. Screenshot of testing with my own email:

3. Thmeleaf template sent as email

  the project needs to introduce thymeleaf dependency, and add: xmlns:th in the new html file=“ http://www.thymeleaf.org ", please move to the previous article.


Here an HTML 5 file of email is created under templates.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8">

<p th:text="${name}"></p>
<a th:text="This is a link" th:href="${link}"></a>
<img th:src="${image1}">

Add another method to the controller.

    public String sendThymeleafMail() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setSubject("This is a thymeleaf Template mail");
        Context context = new Context();
        context.setVariable("name","This is a new one thymeleaf Template");
        String value = templateEngine.process("email.html",context);
        return "Template mail sent successfully";

  code Description:

  • Context belongs to the package org.thymeleaf.context.
  • context.setVariable(), the first parameter is String, and the second is Object type. The first parameter corresponds to the parameter with the same name on the thymeleaf template.
  • templateEngine.process() converts the html file of the specified path to String type return.


5, Summary

  this paper introduces the basic principle of mail sending, SMTP protocol and the summary of POP3 protocol mentioned. Then we introduce dependency together, add project property configuration, and finally explain three kinds of ways to send mail. Source access to see the following!

Topics: Java Spring Thymeleaf SSL network