Spring boot integrated email sending

Keywords: Programming Spring Thymeleaf github SpringBoot

This section describes how to quickly configure and send mail for spring boot project, including simple mail configuration, sending simple mail, sending HTML mail, sending mail with attachments, etc.

The sample source code is: https://github.com/laolunsi/spring-boot-examples

I. mailbox configuration

To ensure that the client login service is enabled in the mailbox used, take 163 mailbox as an example:

Note that in the configuration of sending mail, the user name is the email address and the password is the authorization code here. Other mailboxes, such as QQ and enterprise mailboxes, are also similar configurations. Baidu is not very complicated to suggest.

Let's go straight to the example:

2. Simple email

Create a SpringBoot project and introduce the following dependencies:

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

Note: other dependencies can be added according to their own requirements. If there is any problem, please refer to the sample project.

Fill in the configuration information:

server:
  port: 8012
spring:
  mail:
    host: 'smtp.163.com'
    username: 'xxx@163.com'
    password: 'xxxx' # Authorization code

Write test interface:

@RestController
@RequestMapping(value = "email")
public class EmailAction {

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

    private final JavaMailSender mailSender; // You can also use AutoWired

    public EmailAction(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @PostMapping(value = "simple")
    public String sendSimpleMsg(String msg, String email) {
        if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
            return "Please enter the message to send and the destination mailbox";
        }

        try {
            SimpleMailMessage mail = new SimpleMailMessage();
            mail.setFrom(sendName);
            mail.setTo(email);
            mail.setSubject("This is a simple email");
            mail.setText(msg);
            mailSender.send(mail);
            return "Send successfully";
        } catch (Exception ex) {
            ex.printStackTrace();
            return "fail in send:" + ex.getMessage();
        }
    }
}

Test it:

HTML send

In addition to ordinary text format mail, mail can also be HTML format, so you can customize a rich style!

Sending HTML mail is also very simple. When sending mail, you can specify the content as HTML:

@PostMapping(value = "html")
    public String sendHtmlMsg(String msg, String email) {
        if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
            return "Please enter the message to send and the destination mailbox";
        }
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(sendName);
            messageHelper.setTo(email);
            messageHelper.setSubject("HTML mail");
            String html = "<div><h1><a name=\"hello\"></a><span>Hello</span></h1><blockquote><p><span>this is a html email.</span></p></blockquote><p>&nbsp;</p><p><span>"
                    + msg + "</span></p></div>";
            messageHelper.setText(html, true);
            mailSender.send(message);
            return "Send successfully";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Send failed:" + e.getMessage();
        }
    }

Email with attachments

Sometimes you need to send an email with attachments, such as sending a resume, usually with a PDF file.

Here, we add a PDF file under resources, and then carry this file when sending the email:

@PostMapping(value = "mime_with_file")
    public String sendWithFile(String msg, String email) {
        if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
            return "Please enter the message to send and the destination mailbox";
        }

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(sendName);
            messageHelper.setTo(email);
            messageHelper.setSubject("A message with attachments");
            messageHelper.setText(msg);
            // The file is located in the resources directory
            // The file path can't write the file name directly, the system will report an error and can't find the path, but IDEA can directly map the past
            // The file path can be written as relative path src/main/resources/x.pdf, or as absolute path: System.getProperty("user.dir") + "/src/main/resources/x.pdf"
            File file = new File("src/main/resources/SpringBoot Log processing Logback.pdf");
            //File file = new file (system. Getproperty ("user. Dir") + "/ SRC / main / resources / Logback.pdf" of spring boot log processing);
            System.out.println("File exists:" + file.exists());
            messageHelper.addAttachment(file.getName(), file);
            mailSender.send(message);
            return "Send successfully";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Send failed:" + e.getMessage();
        }
    }

Test it:

HTML with picture send

What if HTML mail contains static resources such as pictures? The picture will be displayed in the mail, so that the mail recipient can see the picture content without downloading the attachment. And the content of the email is more abundant. This function is also very simple. You can use addInline to do this:

@PostMapping(value = "html_with_img")
    public String sendHtmlWithImg(String msg, String email) {
        if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
            return "Please enter the message to send and the destination mailbox";
        }
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(sendName);
            messageHelper.setTo(email);
            messageHelper.setSubject("With static resource pictures HTML mail");
            String html = "<div><h1><a name=\"hello\"></a><span>Hello</span></h1><blockquote><p><span>this is a html email.</span></p></blockquote><p>&nbsp;</p><p><span>"
                    + msg + "</span></p><img src='cid:myImg' /></div>";
            messageHelper.setText(html, true);
            File file = new File("src/main/resources/wei.jpg");
            messageHelper.addInline("myImg", file);
            mailSender.send(message);
            return "Send successfully";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Send failed:" + e.getMessage();
        }
    }

Send mail using templates

With the template engine, such as thymeleaf, you can also send e-mail through the template file:

First, the spring boot starter thymeleaf dependency is introduced:

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

Create a new templates folder under resources, and create an EmailTemplate.html file as follows:

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Mail template</title>
</head>

<body>
    Hello, this is your msg: <span th:text="${msg}"></span>
</body>
</html>
@Autowired
    private TemplateEngine templateEngine;

    @PostMapping(value = "html_with_template")
    public String sendHtmlByTemplate(String msg, String email) {
        if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
            return "Please enter the message to send and the destination mailbox";
        }

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(sendName);
            messageHelper.setTo(email);
            messageHelper.setSubject("Use HTML Template file send mail");

            Context context = new Context();
            context.setVariable("msg", msg);
            messageHelper.setText(templateEngine.process("EmailTemplate", context), true);
            mailSender.send(message);
            return "Send successfully";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Send failed:" + e.getMessage();
        }
    }

Reference resources: https://mrbird.cc/Spring-Boot-Email.html

Communication learning

Personal website: http://www.eknown.cn

GitHub: https://github.com/laolunsi

Public number: apes story, "sharing technology, and understanding life", welcome attention!

Posted by YourNameHere on Thu, 12 Dec 2019 13:41:06 -0800