This article mainly introduces the Spring Boot mail sending, respectively explained the simple text mail, HTML mail, attachment mail, picture mail, template mail.

Quick navigation

  • Adding Maven dependencies
  • Configuration file Added mailbox configurations
  • Service and Test project code construction
  • Description of the five mail sending types
    • Text messages
    • HTML email
    • The attachment mail
    • HTML embedded image mail
    • Template mail
  • The problem summary

Adding Maven dependencies

Introduce the spring-boot-starter-email dependency in the pom. XML file of the Spring Boot project

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

The spring-boot-starter-thymeleaf plugin is required for template mail

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

Configuration file Added mailbox configurations

163 To configure the email address, replace your own account information and enter the password as the authorization code.

application.yml

spring: 
    mail:
        host: smtp.163.com
        username: [email protected]
        password: your163password
        default-encoding: utf-8
Copy the code

For configuring email sending by QQ mailbox, the following password is the authorization code

spring:
    mail:
        host: smtp.qq.com
        username: [email protected]
        password: yourQQpassword
Copy the code

The project build

Written based on the unit test Chapter5-1 code example in the previous section

Business layer code

Create the mailService. Java file in the service directory to write the mail sending function at the service layer

Let’s use the JavaMailSender interface provided by Spring to implement mail sending and use @AutoWired to inject mail sending objects locally in the project

MailService.java

package com.angelo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailService {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired // The mailSender is injected when the project starts
    private JavaMailSender javaMailSender;

    / /... The following will introduce one by one...
}
Copy the code

Unit test layer code

Test Create the MailServiceTest. Java test class in the test directory to unit test the business layer code

MailServiceTest.java

package com.angelo.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

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

import java.lang.reflect.Array;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailService mailService;

    @Resource
    TemplateEngine templateEngine;

    String to = "[email protected]";

    / /... Here is an introduction...
}
Copy the code

Description of the five mail sending types

Text messages

SimpleMailMessage encapsulates the functions of sending and receiving simple emails, as well as the functions of detecting exceptions. It is also the simplest way to send an email. Create an email message object, and set the sender, sending object, subject, and content of an email.

  • The business layerMailService.java
/** * Send text message *@param to
 * @param subject
 * @param content
 */
public void sendTextMail(String to, String subject, String content) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(to); // Send objects
    message.setSubject(subject); // The subject of the message
    message.setText(content); // The content of the email
    message.setFrom(from); // Originator of the message

    javaMailSender.send(message);
}
Copy the code

Unit test the above business code to see how it works

  • Unit test layerMailServiceTest.java
@Test
public void sendTextEmailTest(a) {
    mailService.sendTextMail(to, "Send text mail"."Hello, this is a text email from Spring Boot!");
}
Copy the code
  • The test results

HTML email

Create a helper object based on MimeMessageHelper and set the second parameter of setText to true to print the email in HTML format.

  • The business layerMailService.java
/** * send HTMl mail *@param to
 * @param subject
 * @param content
 * @throws MessagingException
 */
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);

    javaMailSender.send(message);
}
Copy the code
  • Unit test layerMailServiceTest.java
@Test
public void sendHtmlEmailTest(a) throws MessagingException {
    String content = "<html>" +
            "<body>" +
                "<h1 style=\"" + "color:red;" + "\"> Hello, this is an HTML email sent by Spring Boot " +
            "</body></html>";

    mailService.sendHtmlMail(to, "Send HTML mail", content);
}
Copy the code
  • The test results

You can see that the message results use the pre-set message format in the example

The attachment mail

  • The business layerMailService.java
    /** * Send message with attachment *@param to
     * @param subject
     * @param content
     * @param filePathList
     * @throws MessagingException
     */
    public void sendAttachmentMail(String to, String subject, String content, String[] filePathList) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        for (String filePath: filePathList) {
            System.out.println(filePath);

            FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
            String fileName = fileSystemResource.getFilename();
            helper.addAttachment(fileName, fileSystemResource);
        }

        javaMailSender.send(message);
    }
Copy the code

FilePathList says your attachment file path, array format.

  • Unit test layerMailServiceTest.java
    @Test
    public void sendAttachmentEmailTest(a) throws MessagingException {
        String[] filePathList = new String[2];
        filePathList[0] = "/SpringBoot-WebApi/chapter4.zip";
        filePathList[1] = "/SpringBoot-WebApi/chapter5.zip";

        mailService.sendAttachmentMail(to, "Send attached mail"."Hello, this is an attached email from Spring Boot!", filePathList);
    }
Copy the code
  • The test results

HTML embedded image mail

Also based on HTML email, through embedded static resources such as images, you can see the images directly.

  • The business layerMailService.java
    /** * Send HTML embedded image *@param to
     * @param subject
     * @param content
     * @param srcPath
     * @param srcId
     * @throws MessagingException
     */
    public void sendHtmlInlinePhotoMail(String to, String subject, String content, String srcPath, String srcId) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        FileSystemResource fileSystemResource = new FileSystemResource(new File(srcPath));
        helper.addInline(srcId, fileSystemResource);

        javaMailSender.send(message);
    }
Copy the code

In the following unit tests, srcPath is your local image path. SrcId must be the same as that of helper.addInline(srcId, fileSystemResource)srcId for the business layer.

  • Unit test layerMailServiceTest.java
    @Test
    public void sendHtmlInlinePhotoMailTest(a) throws MessagingException {
        String srcPath = "/SpringBoot-WebApi/chapter6/img/pic18.jpg";
        String srcId = "pic18";
        String content = "<html>" +
                "<body>" +
                "

Hello, this is an htML-embedded image email sent by Spring Boot

"
+ "<img src=\'cid:"+ srcId +"\'></img>" + "</body></html>"; mailService.sendHtmlInlinePhotoMail(to, "Send picture mail", content, srcPath, srcId); } Copy the code
  • The test results

Template mail

If the email content is relatively simple, we can choose to use the above simple email sending methods. In complex business, THE HTML structure is needed and the DATA in THE HTML needs to be dynamically modified. Or we can choose template email, such as Freemarker and Thymeleaf template engine. This section focuses on using Thymeleaf.

  • Email template writing

Create the emailtemplate. HTML file in the Resources/Templates directory


      
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Template mail</title>
</head>
<body>How do you do?<span th:text="${username}"></span>Welcome to my personal blog:<a href="https://github.com/Q-Angelo/summarize">Github</a>,<a th:href="@{https://www.imooc.com/u/{id}(id=${id})}" href="#">For class network</a>
</body>
</html>
Copy the code

Just use the HTML mail described above to add a method to the unit test file to test.

  • Unit test layerMailServiceTest.java
@Test
public void testTemplateEmailTest(a) throws MessagingException {
    Context context = new Context();
    context.setVariable("username"."Zhang");
    context.setVariable("id"."2667395");

    String emailContent = templateEngine.process("emailTemplate", context);

    mailService.sendHtmlMail(to, "Send template mail", emailContent);
}
Copy the code
  • The test results

Q&A

The reason for this mistake is that netease treated the email I sent as spam. << send 163 text email >> this is the title of the email I filled in. Later, IT was found that netease caused the inclusion of 163 in the title.

com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 163 smtp10,DsCowADH1MxWegtcyxFjDw--.48939S2 1544256086
Copy the code

If you have any questions, please ask them in the comments section below

Github see the full example chapter6-1 for this article

Author: you may link: www.imooc.com/article/267… Github: Spring Boot