This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

Introduction to SpringBoot series email sending posture

Mail, in the actual project development, may not much more special, if there is no specific requirements, believe that also does not have how many friends will be specially to pay attention, so if we want to make a project now exception alarm system, when an exception, can send email to the specified, so let’s achieve this function, What can be done?

How to use SpringBoot encapsulated MailSender to send mail

I. Project environment

1. Project dependency

This project is developed with SpringBoot 2.2.1.RELEASE + Maven 3.5.3 + IDEA

Start a Web service for testing

<dependencies>
    <! -- Core dependencies for mail delivery -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <! -- Suitable for sending HTML template mail, using freemarker to render HTML template --> freemarker
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
</dependencies>
Copy the code

2. The configuration

Before you begin, we need to prepare a first used to send mail account, for example, I used here 163 E-mail to send mail, need to first email providers where obtaining authorization code, specific how to get this thing, different mailbox pose some is different, each friend according to own actual situation, search for, believe that will soon be able to get to

Here is a brief introduction to how to obtain netease Email

Next, set the configuration information related to sending the email. The configuration file is application.yml

spring:
  # Email configuration
  mail:
    host: smtp.163.com
    from: [email protected]
    # Fill in your own sender username + authorization code
    username:
    password:
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
Copy the code

II. Sending emails

We’ll start with the basics of text mailing, and work our way through how to add attachments, use beautiful HTML templates, and so on

1. Send a simple text email

We are directly using the JavaMailSender here to send a basic text message

@Service
public class MailDemo {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.from:[email protected]}")
    private String from;

    private void basicSend(a) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // The sender of the email
        simpleMailMessage.setFrom(from);
        // The email receiver can be more than one, and the parameters are variable parameters
        simpleMailMessage.setTo("[email protected]");
        // The subject of the email is the subject
        simpleMailMessage.setSubject("SpringBoot Test Email sending");
        // Email content
        simpleMailMessage.setText("Simple message body"); javaMailSender.send(simpleMailMessage); }}Copy the code
  • JavaMailSender: Used directly as a Spring bean object
  • SimpleMailMessage: Simple mail object with some basic information associated with sending a message
    • From: the sender
    • The person to whom an email is to be replied
    • To: the recipient
    • Cc: cc
    • BCC: close to send
    • Subject: Indicates the subject of an email
    • Text: Indicates the email body in text format
    • Date: Indicates the time when the email is sent

2. Send HTML

For simple text mails, the above basic is enough, if we want the content of the mail to be a little more beautiful, we can use HTML to achieve the layout

Instead of SimpleMailMessage above, MimeMessage is used to deliver HTML content

The use of posture is similar to the above, except that the body is HTML text

/** * send HTML */
public void sendHtml(a) throws MessagingException {
    MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
    mimeMessageHelper.setFrom(from);
    mimeMessageHelper.setTo("[email protected]");
    mimeMessageHelper.setSubject("SpringBoot Test Email sending");

    // Email content
    mimeMessageHelper.setText("<h1>Hello World</h1> <br/> " +
            "< div > welcome to < a href = \ \" https://blog.hhui.top\ "> a dusty blog address < / a > < br / >" +
            " <img width=\"200px\" height=\"200px\" src=\"https://blog.hhui.top/hexblog/imgs/info/wx.jpg\"/>" +
            "</div>".true);

    javaMailSender.send(mimeMailMessage);
}
Copy the code

Focus on

  • Notice abovesetTextMethod, which must be true, or it will be sent as text

3. Add attachments

We can directly select the attachment to upload when we write the email, so what difference does the implementation of the code make?

/** * Send attachment */
public void sendWithFile(a) throws MessagingException, IOException {
    MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
    mimeMessageHelper.setFrom(from);
    mimeMessageHelper.setTo("[email protected]");
    mimeMessageHelper.setSubject("SpringBoot Test Email sending");

    mimeMessageHelper.setText("<h1>Hello World</h1> <br/> " +
            "< div > welcome to < a href = \ \" https://blog.hhui.top\ "> a dusty blog address < / a > < br / >" +
            " <img width=\"200px\" height=\"200px\" src=\"https://blog.hhui.top/hexblog/imgs/info/wx.jpg\"/>" +
            "</div>");

    String url = "https://blog.hhui.top/hexblog/imgs/info/wx.jpg";
    URL imgUrl = new URL(url);
    mimeMessageHelper.addAttachment("img.jpg", imgUrl::openStream);

    javaMailSender.send(mimeMailMessage);
}
Copy the code

Notice that the above implementation is not much different from the previous one. The key point is the attachment. In the above implementation, a picture is added to the attachment

4. Freemaker template

The above HTML send, will find that we need to assemble the HTML body, this operation may not be very nice, with the help of the page rendering engine to achieve email template support, can be said to be a more common solution, here is a brief introduction to the realization of Freemaker posture, As for themlaf, beef or JSP, there is no big difference

First write an email template resources/template/mail. The FTL

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="SpringBoot thymeleaf"/>
    <meta name="author" content="YiHui"/>
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0"/>
    <title>Mail template</title>
</head>
<style>
    .title {
        color: #c00;
        font-weight: normal;
        font-size: 2em;
    }

    .content {
        color: darkblue;
        font-size: 1.2 em;
    }

    .sign {
        color: lightgray;
        font-size: 0.8 em;
        font-style: italic;
    }
</style>
<body>

<div>
    <div class="title">${title}</div>
    <div class="content">${content}</div>
</div>
</body>
</html>
Copy the code

In the template above, we define two variables, title and content, and these are the values we need to replace

Next up is the mail sending instance

import freemarker.template.Configuration;

@Autowired
private Configuration configuration;

/* freemarker template */
public void freeMakerTemplate(a) throws MessagingException, IOException, TemplateException {
    MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
    mimeMessageHelper.setFrom(from);
    mimeMessageHelper.setTo("[email protected]");
    mimeMessageHelper.setSubject("SpringBoot Test Email sending");

    Map<String, Object> map = new HashMap<>();
    map.put("title"."Subject line");
    map.put("content"."Message Body");
    String text = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), map);
    mimeMessageHelper.setText(text, true);

    String url = "https://blog.hhui.top/hexblog/imgs/info/wx.jpg";
    URL imgUrl = new URL(url);
    mimeMessageHelper.addAttachment("img.jpg", imgUrl::openStream);

    javaMailSender.send(mimeMailMessage);
}
Copy the code

Notice the above implementation. The key point is to use FreeMarkerTemplateUtils to render the template and output the HTML body, so if you want to use another template rendering engine, change this

5. Test and summary

Finally, simply invoke the above implementation to see if the mail can be sent successfully

This post introduces how to send an email, and gives examples for simple text emails, HTML bodies, attachments, etc. It’s not hard to look at posture as a whole, but there are a few email terms you can learn about

  • To: To the people to whom the email is sent
  • Cc: Cc, usually a cc list, just to make him aware that there is an email, that it belongs to a known person
  • BCC: BCC, unlike the above two, the recipient and cc do not know who the BCC was sent to, this is the biggest difference, to be honest, I have never used this device

In the next blog post, I will look at how to associate the log log with sending mail. When an exception occurs, send mail to the developer

III. Can’t miss the source code and related knowledge

0. Project

  • Project: github.com/liuyueyi/sp…
  • Source: github.com/liuyueyi/sp…

1. Wechat official account: a gray Blog

The above content is not as good as the letter, purely the words of a family, due to the limited personal ability, there are inevitably omissions and mistakes, such as found bugs or better suggestions, welcome criticism and correction, not grudging gratitude

Below a gray personal blog, record all study and work in the blog, welcome everyone to visit

  • A gray Blog personal Blog blog.hhui. Top
  • A Gray Blog-Spring feature Blog Spring.hhui. Top