SpringBoot plus email, do you have any ideas?

“This is the 22nd day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

1. Enable the MAILBOX POP3/SMTP service

After logging in to QQ mailbox, click the Settings in the upper left and select your account, as shown in the picture below.

Then slide down to POP3/SMTP service as shown in the picture below. Click on “Enable” to send a text message to the specified number and receive an authorization code. This authorization code will be used in appliction.properties configuration

2. Add dependencies to the Springboot project

Create the SpringBoot project and add the email dependency

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

My dependence is as follows:

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.5.3</version>
    </dependency>

    <! -- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>

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

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

</dependencies>
Copy the code

3. Configuration file

# # # # # # qq mailbox # # # # # # # #
# agreement
spring.mail.protocol=smtp
# email server address
spring.mail.host=smtp.qq.com
# email server address
spring.mail.username=[email protected]
# The password is not the login password, but the client authorization code set after POP3 is enabled
Email password will be given to you when POP3/SMTP service is enabled
spring.mail.password=POP3/SMTP service password
# Encoding format
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
If you want to use port 465, add the following configuration:
spring.mail.port=465
spring.mail.properties.mail.smtp.ssl.enable=true
Copy the code

4. Mail service operations

Springboot reference modules usually provide an xxxTmplate for our development. We can encapsulate an EmailTmplate

package com.ljw.task.config;

import lombok.Getter;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.IContext;

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

/ * * *@Description: Mail operation class *@Author: jianweil
 * @date: 2021/11/19 15:07 * /
@Service
@Getter
public class EmailTemplate {

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private TemplateEngine templateEngine;

    //@Resource
    //private MailProperties mailProperties;

    /** * Send a simple text message **@paramFrom sender email *@paramTo recipient email *@paramSubject Mail subject *@paramText Indicates the email content */
    public void sendTextMail(String from, String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        / / the sender
        message.setFrom(from);
        / / the recipient
        message.setTo(to);
        // The subject of the message
        message.setSubject(subject);
        // The content of the email
        message.setText(text);
        javaMailSender.send(message);
    }


    /** * send Html message **@paramFrom sender email *@paramTo recipient email *@paramSubject Mail subject *@paramHTML Mail content with the HTML tag */
    public void sendHtmlMail(String from, String to, String subject, String html) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(html, true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging Exception !", e); }}/** ** Send the attached email **@paramFrom sender email *@paramTo recipient email *@paramSubject Mail subject *@paramText Indicates the email content *@paramAttachmentFilename Attachment name *@paramThe file attachment * /
    public void sendAttachmentMail(String from, String to, String subject, String text, String attachmentFilename, FileSystemResource file) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);
            // Add mail
            helper.addAttachment(attachmentFilename, file);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging Exception !", e); }}/** * Sends an inline resource message **@paramFrom sender email *@paramTo recipient email *@paramSubject Mail subject *@param<img SRC ='cid:" + contentId + "' ></body></ HTML >"; </body></ HTML > *@paramContentId Inline file ID *@paramThe file file * /
    public void sendInlineResourceMail(String from, String to, String subject, String text, String contentId, FileSystemResource file) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true);
            helper.addInline(contentId, file);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging Exception !", e); }}/** * Send template message **@paramFrom sender email *@paramTo recipient email *@paramSubject Mail subject *@paramContext content class, which matches the template parameters. The id parameter is myValuesitest: * context context = new Context(); * context.setVariable("id","myvaluesitest"); *@paramThe template templates directory template file name, such as templates/emailTemplate. HTML is spread: emailTemplate * /
    public void sendTemplateMail(String from, String to, String subject, IContext context, String template) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            String text = templateEngine.process(template, context);
            helper.setText(text, true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging Exception !", e); }}}Copy the code

5. The test class

package com.ljw.task.config;

import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.File;

/ * * *@Description: todo
 * @Author: jianweil
 * @date: 2021/11/21 a little * /
@SpringBootTest
class EmailTemplateTest {

    @Resource
    private EmailTemplate emailTemplate;
    @Resource
    private MailProperties mailProperties;

    public String getSender(a) {
        return mailProperties.getUsername();
    }

    public String getReceiver(a) {
        return mailProperties.getUsername();
    }

    /** * text */
    @Test
    void sendTextMail(a) {
        emailTemplate.sendTextMail(getSender(), getReceiver(), "Title: sendTextMail"."Textual content");
    }

    /** ** with HTML tag */
    @Test
    void sendHtmlMail(a) {
        StringBuffer sb = new StringBuffer();
        sb.append("

headline -h1

"
) .append("

) .append("

); emailTemplate.sendHtmlMail(getSender(), getReceiver(), "Title: sendHtmlMail", sb.toString()); } /** ** with attachments */ @Test void sendAttachmentMail(a) { FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/images/avatar.jpg")); emailTemplate.sendAttachmentMail(getSender(), getReceiver(), "Title: Sendata Post Mail"."I have sent you an attachment for your attention."."Attachment name.jpg", file); } /** * Sends an inline resource message */ @Test void sendInlineResourceMail(a) { String imgId = "avatar"; String content = + imgId + "' ></body></html>"; FileSystemResource res = new FileSystemResource(new File("src/main/resources/static/images/avatar.jpg")); emailTemplate.sendInlineResourceMail(getSender(), getReceiver(), "Title: sendInlineResourceMail", content, imgId, res); } /*** * Send template email */ @Test void sendTemplateMail(a) { Context context = new Context(); context.setVariable("id"."hello"); emailTemplate.sendTemplateMail(getSender(), getReceiver(), "Title: sendTemplateMail", context, "helloTemplate"); }}Copy the code

The template class used to send template emails: helloTemplate.html

HelloTemplate. HTML:

<! DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/> <title> </head> <body> Hello, this is template mail, please click the link below to complete the jump, <a href="#" th:href="@{'http://www.baidu.com/s?wd='+${id}}"< p style = "max-width: 100%; clear: both; min-height: 1em" ${id}"> < / a >. </body> </html>Copy the code

The image used to send the attachment: Avatar.jpg

Avatar. JPG:

Instead of Posting a screenshot of the email sent by test, replace sender and receiver with your own email address and test it yourself.

6. Analyze common services

  1. Scenarios in which users need to activate their accounts after registration:

After successful registration, the user saves the data to Redis, sets the expiration time, and sends an email message to the specified mailbox. The email contains a hyperlink with the key uniquely identified by the user. The user clicks the hyperlink to return to our activation interface, and the user will be activated if the information is correct. If the activation is not clicked within the set time, the activation fails.

  1. Other notification scenarios