SoFunction
Updated on 2025-03-04

SpringBoot integrates Mail to easily realize automatic email push function

Simple use

1. Pom package configuration

Add spring-boot-starter-mail package reference to the pom package

<dependencies>
    <dependency> 
        <groupId></groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency> 
</dependencies>

2. Add mailbox configuration in

=. //Email Server Address=xxx@ //username=xxyyooo    //password-encoding=UTF-8
 
=xxx@  //Who will send the email

3. Write mailService, only implementation classes are proposed here.

@Component
public class MailServiceImpl implements MailService{
 
    private final Logger logger = (());
 
 
    @Autowired
    private JavaMailSender mailSender;
 
    @Value("${}")
    private String from;
 
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        (from);
        (to);
        (subject);
        (content);
 
        try {
            (message);
            ("Simple email has been sent.");
        } catch (Exception e) {
            ("Exception occurred while sending a simple email!", e);
        }
    }
}

4. Write test class for testing

@RunWith()
@SpringBootTest
public class MailServiceTest {
 
    @Autowired
    private MailService MailService;
 
    @Test
    public void testSimpleMail() throws Exception {
        ("test@","test simple mail"," hello this is simple mail");
    }
}   

At this point, a simple text sending is complete.

Advanced gameplay

However, during normal use, we usually add pictures or attachments to the email to enrich the content of the email. The following is how to use Spring Boot to send rich emails.

Send html format email

The other thing remains unchanged and add the sendHtmlMail method in MailService.

public void sendHtmlMail(String to, String subject, String content) {
    MimeMessage message = ();
 
    try {
        //true means that you need to create a multipart message        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        (from);
        (to);
        (subject);
        (content, true);
 
        (message);
        ("html mail sent successfully");
    } catch (MessagingException e) {
        ("Exception occurred while sending html mail!", e);
    }
}

Build html content in the test class and send the test

@Test
public void testHtmlMail() throws Exception {
    String content="&lt;html&gt;\n" +
            "&lt;body&gt;\n" +
            " <h3>hello world ! This is an Html email!</h3>\n" +
            "&lt;/body&gt;\n" +
            "&lt;/html&gt;";
    ("test@","test simple mail",content);
}

Send emails with attachments

Add the sendAttachmentsMail method in MailService.

public void sendAttachmentsMail(String to, String subject, String content, String filePath){
    MimeMessage message = ();
 
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        (from);
        (to);
        (subject);
        (content, true);
 
        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = (());
        (fileName, file);
 
        (message);
        ("The email with attachment has been sent.");
    } catch (MessagingException e) {
        ("Exception occurred while sending an email with attachment!", e);
    }
}

Adding multiple attachments can use multiple (fileName, file)

Add test method to test class

@Test
public void sendAttachmentsMail() {
    String filePath="e:\\tmp\\";
    ("test@", "Subject: Email with attachments", "If there are attachments, please check them!", filePath);
}

Send mail with static resources

Static resources in emails generally refer to images. Add the sendAttachmentsMail method to MailService.

public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
    MimeMessage message = ();
 
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        (from);
        (to);
        (subject);
        (content, true);
 
        FileSystemResource res = new FileSystemResource(new File(rscPath));
        (rscId, res);
 
        (message);
        ("The mail embedded in the static resource has been sent.");
    } catch (MessagingException e) {
        ("Exception occurred while sending emails embedded with static resources!", e);
    }
}

Add test method to test class

@Test
public void sendInlineResourceMail() {
    String rscId = "neo006";
    String content="&lt;html&gt;&lt;body&gt;This is an email with pictures:&lt;img src=\'cid:" + rscId + "\' &gt;&lt;/body&gt;&lt;/html&gt;";
    String imgPath = "C:\\Users\\summer\\Pictures\\";
 
    ("test@", "Subject: This is an email with pictures", content, imgPath, rscId);
}

Adding multiple images can be achieved using multiple <imgsrc='cid:" + rscId + "'>  and (rscId,res)

All email sending services have been completed here.

Email system

These are the basic services for sending emails above, but if we want to build a mail system, we still need to consider the following issues:

Email Template

We often receive emails like this:

Dear xxx user:
 
Congratulations on registering as a user of xxx.com. At the same time, thank you for your attention and support for xxx and welcome you to use xx's products and services.
    ...

Among them, only the username xxx is changing, and the content of other emails remains unchanged. If you need to manually splice each email, it will not be elegant enough. It is also inconvenient to modify the code every time the template is modified. Therefore, it is recommended to make an email template to handle this type of email needs. The essence of a template is very simple, it is to replace the changed parameters in the template and convert them into an html string. Here we use thymeleaf as an example to demonstrate.

1. Import thymeleaf packages in pom

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. Create under resources/templates

&lt;!DOCTYPE html&gt;
&lt;html lang="zh" xmlns:th=""&gt;
    &lt;head&gt;
        &lt;meta charset="UTF-8"/&gt;
        &lt;title&gt;Title&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        Hello,This is a verification email,Please click the link below to complete the verification,&lt;br/&gt;
        &lt;a href="#" rel="external nofollow" th:href="@{ /{id}(id=${id}) }" rel="external nofollow" >Activate the account</a>    &lt;/body&gt;
 
&lt;/html&gt;

3. Analyze the template and send it

@Test
public void sendTemplateMail() {
    //Create email text    Context context = new Context();
    ("id", "006");
    String emailContent = ("emailTemplate", context);
 
    ("test@","Subject: This is a template email",emailContent);
}

Send failed

Due to various reasons, there will always be cases where emails are sent, such as: emails are sent too frequently, network abnormalities, etc. When this happens, we generally consider retrying the email, which will be divided into the following steps:

  • 1. When receiving the sending email request, first record the request and enter the database.

  • 2. Send emails using the mail sending interface and record the sending results into the library.

  • 3. During the scanning time period of the startup time system, emails that have not been sent successfully and retryed less than 3 times will be sent again.

Asynchronous send

Many times, email sending is not a result that our main business must pay attention to. For example, notification and reminder businesses can allow delays or failures. At this time, you can use asynchronous methods to speed up the execution of the main transaction. In actual projects, you can use MQ to send emails and start sending emails after listening to the message queue.

The above is the detailed content of SpringBoot integrating Mail to easily implement automatic email push function. For more information about SpringBoot Mail email push, please follow my other related articles!