[TOC]

1, the preface

Sending emails should be one of the common functions. Whether it is registration and activation of users, account membership expiration reminder, or business marketing information prompt, the system needs to automatically send emails to users.

So how does Spring Boot send emails?

Spring introduced JavaMailSender to simplify the process of sending emails, and now Spring Boot encapsulates it.

That is the spring-boot-starter-mail dependency package.

2. Install dependencies

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

3. Add configuration information

src/main/resources/application.yml

server:
  port: 9002

spring:
  mail:
    host: smtp.qq.com
    username: 149807666@qq.com
    password: sputxytreefvxrgoihef
  resources:
    static-locations: classpath:/resources/, classpath:/static/ ,classpath:/templates/

mail:
  fromMail:
    addr: [email protected] # emailer

# log level
logging:
  level:
    root: warn
    com.scaffold.test.mapper: trace
    com.scaffold.test.task: trace

Copy the code

Here we take QQ email as an example. Smtp.qq.com is the address of the email server.

Username is your email address, password is your email password.

Mai.frommail.addr is the email address of the sender.

4. Code implementation

The Entity – Mail message Entity class: com. Scaffold. Test. The Entity. The Mail

package com.scaffold.test.entity;

import lombok.Data;

@Data
public class Mail {

    // To whom
    private String to;

    // Send the subject
    private String subject;

    // Send the content
    private String content;

    // Attached address
    private String filePath;
}

Copy the code

Service – mail Service interface: com. Scaffold. Test. Service. The MailService

package com.scaffold.test.service;

import com.scaffold.test.entity.Mail;

public interface MailService {
    // Send an email
    public void sendMail(Mail mail);
}

Copy the code

ServiceImpl – mail service interface implementation class: com. Scaffold. Test. Service. The impl. MailServiceImpl

package com.scaffold.test.service.impl;

import com.scaffold.test.entity.Mail;
import com.scaffold.test.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.internet.MimeMessage;
import java.io.File;

@Service
public class MailServiceImpl implements MailService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.fromMail.addr}")
    private String mailFrom;

    // Only text is sent
    @Override
    public void sendMail(Mail mail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailFrom);
        message.setTo(mail.getTo());
        message.setSubject(mail.getSubject());
        message.setText(mail.getContent());
        mailSender.send(message);
        logger.info("Sent complete"); }}Copy the code

Controller – email Controller: com. Scaffold. Test. Controller. MailController

package com.scaffold.test.controller;

import com.scaffold.test.base.Result;
import com.scaffold.test.base.ResultGenerator;
import com.scaffold.test.entity.Mail;
import com.scaffold.test.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;

@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private MailService mailService;

    // Send unformatted text
    @Async
    @GetMapping("post")
    public Result postMail(a) {
        Mail mail = new Mail();
        mail.setTo("******@qq.com");
        mail.setSubject("automatic");
        mail.setContent(Automatic mail publishing);
        mailService.sendMail(mail);
        return ResultGenerator.getSuccessResult().setMessage("Sent successfully"); }}Copy the code

Note that the @async annotation is used in our code, which means that the operation is asynchronous, so the returned Result will be invalid. I will not comment on the invalid code, because the original code is synchronous.

In fact, it is correct to use asynchrony. In business code, mail delivery is not the focus of the business and can be delayed or failed, so there is no need to occupy the main process;

The result is shown below:

Now that the simple emailing function is complete, if you want to automatically publish, you need to add a scheduled task, see the previous article:

Spring Boot Hands-on teaching (5) : Timed tasks

I won’t repeat it here;

5. Function expansion

5.1 send an EMAIL in HTML format

To send plain text, sometimes not so satisfying as our business requirements, we need to send an email with HTML format as follows:

Added in the MailService sendHtmlMail methods: com. Scaffold. Test. Service. The MailService

package com.scaffold.test.service;

import com.scaffold.test.entity.Mail;

import javax.mail.MessagingException;

public interface MailService {
    // Send an email
    public void sendMail(Mail mail);

    // Send Html mail
    public void sendHtmlMail(Mail mail) throws MessagingException;

}
Copy the code

Corresponding implementation method: com. Scaffold. Test. Service. Impl. MailServiceImpl

		// Send Html mail
    @Override
    public void sendHtmlMail(Mail mail) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            message.setFrom(mailFrom);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getContent(), true);

            mailSender.send(message);
            logger.info("Sending Html message successful");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Failed to send Html message"); }}Copy the code

Controller calls: com. Scaffold. Test. Controller. MailController

		// Send Html mail
    @Async
    @GetMapping("postHtml")
    public Result postHtmlMail(a) throws MessagingException {
        String content = "<html>\n" +
                "<body>\n" +
                "

hello! test Html test!

\n"
+ "</body>\n" + "</html>"; Mail mail = new Mail(); mail.setTo("******@qq.com"); mail.setSubject("Html mail"); mail.setContent(content); mailService.sendHtmlMail(mail); return ResultGenerator.getSuccessResult().setMessage("Sent successfully"); } Copy the code

The result is shown below:

5.2. Send an email with attachments

Sometimes we need to send emails with attachments;

Added in the MailService sendAttachmentsMail methods: com. Scaffold. Test. Service. The MailService

package com.scaffold.test.service;

import com.scaffold.test.entity.Mail;

import javax.mail.MessagingException;

public interface MailService {
    // Send an email
    public void sendMail(Mail mail);

    // Send Html mail
    public void sendHtmlMail(Mail mail) throws MessagingException;

    // Send mail with attachments
    public void sendAttachmentsMail(Mail mail) throws MessagingException;
}

Copy the code

The corresponding implementation class methods: com. Scaffold. Test. Service. Impl. MailServiceImpl

    // Send mail with attachments
    @Override
    public void sendAttachmentsMail(Mail mail) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            message.setFrom(mailFrom);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getContent(), true);

            / / accessories
            FileSystemResource resourse = new FileSystemResource(new File(mail.getFilePath()));
            // Add attachments
            helper.addAttachment("test.png", resourse);

            mailSender.send(message);
            logger.info("Email sent successfully");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Failed to send mail"); }}Copy the code

Controller calls: com. Scaffold. Test. Controller. MailController

    // Send mail with attachments
    @Async
    @GetMapping("postAttachment")
    public Result postAttachmentsMail(a) throws MessagingException {
        Mail mail = new Mail();
        mail.setTo("***@qq.com");
        mail.setSubject("Accessories");
        mail.setContent("There's an attachment. Take a look.");
        mail.setFilePath("E:\\test.png");
        mailService.sendAttachmentsMail(mail);
        return ResultGenerator.getSuccessResult().setMessage("Sent successfully");
    }
Copy the code

The effect is as follows:

5.3, use,thymeleafTemplate to send mail

In addition, for good formatting, we sometimes need to use templates to send emails;

Here we use thymeleaf:

Install dependencies

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

<dependency>
    <groupId>ognl</groupId>
    <artifactId>ognl</artifactId>
    <version>3.2.14</version>
</dpendency>
Copy the code

Controller calls: com. Scaffold. Test. Controller. MailController

 	@Autowired
    private SpringTemplateEngine templateEngine;

    // Send an Html template email
    @Async
    @GetMapping("postTemplate")
    public void postTemplateMail(a) throws MessagingException {
        Context context = new Context();
        Map<String, Object> emailParam = new HashMap<>();
        emailParam.put("name"."Change the name of product Terminal");
        emailParam.put("content"."Niuniu Terminal");
        emailParam.put("person"."Alex Wong");
        context.setVariable("emailParam", emailParam);
        String emailTemplate = templateEngine.process("emailTemplate", context);

        Mail mail = new Mail();
        mail.setTo("*****@qq.com");
        mail.setSubject("Template mail");
        mail.setContent(emailTemplate);
        mailService.sendHtmlMail(mail);
    }
Copy the code

Template file: SRC/main/resources/templates/emailTemplate. HTML


      
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0"/>
    <title>mail</title>
</head>
<body>


<table align="center" cellpadding="0" cellspacing="0" width="600px">
    <tr>
        <td>
            <table align="center" border="0" cellpadding="0" cellspacing="0" width="600"
                   style="border-collapse: collapse;">
                <tr>
                    <td align="center" style="padding: 40px 0 30px 0;">
                        <img src='Your picture address' style='width: 183 px height: 47.50 px'>
                    </td>
                </tr>

                <tr>
                    <td bgcolor="#ffffff" style="padding: 0px 30px 20px 30px">
                        <h3>Product name change notice</h3>

                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                            <tr>
                                <td colspan="2" style="padding: 0 0 3px 0">Notice:<span th:text="${emailParam.name}"></span>
                                </td>
                            </tr>
                            <tr>
                                <td style="padding: 12px 0 3px 0">Product Name:<span th:text="${emailParam.content}"></span>
                                </td>
                            </tr>
                            <tr>
                                <td style="padding: 12px 0 3px">The approver:<span th:text="${emailParam.person}"></span>
                                </td>
                            </tr>

                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>

</table>
</body>
</html>
Copy the code

The effect is as follows:

6. Complete code

The Entity – Mail message Entity class: com. Scaffold. Test. The Entity. The Mail

package com.scaffold.test.entity;

import lombok.Data;

@Data
public class Mail {

    // To whom
    private String to;

    // Send the subject
    private String subject;

    // Send the content
    private String content;

    // Attached address
    private String filePath;
}

Copy the code

Service – mail Service interface: com. Scaffold. Test. Service. The MailService

package com.scaffold.test.service;

import com.scaffold.test.entity.Mail;

import javax.mail.MessagingException;

public interface MailService {
    // Send an email
    public void sendMail(Mail mail);

    // Send Html mail
    public void sendHtmlMail(Mail mail) throws MessagingException;

    // Send mail with attachments
    public void sendAttachmentsMail(Mail mail) throws MessagingException;
}
Copy the code

ServiceImpl – mail service interface implementation class: com. Scaffold. Test. Service. The impl. MailServiceImpl

package com.scaffold.test.service.impl;

import com.scaffold.test.entity.Mail;
import com.scaffold.test.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.internet.MimeMessage;
import java.io.File;

@Service
public class MailServiceImpl implements MailService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.fromMail.addr}")
    private String mailFrom;

    // Only text is sent
    @Override
    public void sendMail(Mail mail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailFrom);
        message.setTo(mail.getTo());
        message.setSubject(mail.getSubject());
        message.setText(mail.getContent());
        mailSender.send(message);
        logger.info("Sent complete");
    }

    // Send Html mail
    @Override
    public void sendHtmlMail(Mail mail) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            message.setFrom(mailFrom);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getContent(), true);

            mailSender.send(message);
            logger.info("Sending Html message successful");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Failed to send Html message"); }}// Send mail with attachments
    @Override
    public void sendAttachmentsMail(Mail mail) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            message.setFrom(mailFrom);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getContent(), true);

            / / accessories
            FileSystemResource resourse = new FileSystemResource(new File(mail.getFilePath()));
            // Add attachments
            helper.addAttachment("test.png", resourse);

            mailSender.send(message);
            logger.info("Email sent successfully");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Failed to send mail"); }}}Copy the code

Controller – email Controller: com. Scaffold. Test. Controller. MailController

package com.scaffold.test.controller;

import com.scaffold.test.entity.Mail;
import com.scaffold.test.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private MailService mailService;

    @Autowired
    private SpringTemplateEngine templateEngine;

    // Send unformatted text
    @Async
    @GetMapping("post")
    public void postMail(a) {
        Mail mail = new Mail();
        mail.setTo("**@qq.com");
        mail.setSubject("automatic");
        mail.setContent(Automatic mail publishing);
        mailService.sendMail(mail);
/ / return ResultGenerator. GetSuccessResult (.) setMessage (" send success ");
    }

    // Send Html mail
    @Async
    @GetMapping("postHtml")
    public void postHtmlMail(a) throws MessagingException {
        String content = "<html>\n" +
                "<body>\n" +
                "

hello! test Html test!

\n"
+ "</body>\n" + "</html>"; Mail mail = new Mail(); mail.setTo("***@qq.com"); mail.setSubject("Html mail"); mail.setContent(content); mailService.sendHtmlMail(mail); / / return ResultGenerator. GetSuccessResult (.) setMessage (" send success "); } // Send mail with attachments @Async @GetMapping("postAttachment") public void postAttachmentsMail(a) throws MessagingException { Mail mail = new Mail(); mail.setTo("****@qq.com"); mail.setSubject("Accessories"); mail.setContent("There's an attachment. Take a look."); mail.setFilePath("E:\\test.png"); mailService.sendAttachmentsMail(mail); / / return ResultGenerator. GetSuccessResult (.) setMessage (" send success "); } // Send an Html template email @Async @GetMapping("postTemplate") public void postTemplateMail(a) throws MessagingException { Context context = new Context(); Map<String, Object> emailParam = new HashMap<>(); emailParam.put("name"."Change the name of product Terminal"); emailParam.put("content"."Niuniu Terminal"); emailParam.put("person"."Alex Wong"); context.setVariable("emailParam", emailParam); String emailTemplate = templateEngine.process("emailTemplate", context); Mail mail = new Mail(); mail.setTo("***@qq.com"); mail.setSubject("Template mail"); mail.setContent(emailTemplate); mailService.sendHtmlMail(mail); / / return ResultGenerator. GetSuccessResult (.) setMessage (" send success ");}}Copy the code