@[toc] Spring Boot send mail, Songko has written a special article before, here will not be verbose. If you don’t know how Spring Boot sends emails, turn to the second half of this article.

Today I want to talk with you about SMTP server port problem, this is also a small partner raised questions, SMTP server has many ports: 25, 465, 587 what is the difference between them? Can I use it at will? Hopefully today’s post will give you some answers.

1. What is SMTP

SMTP stands for Simple Mail Transfer Protocol, in short, it is the process of sending E-mail over the Internet. A computer port is a way for a personal computer to connect to a network and complete data transfer. An SMTP port is a combination of the two: a port designed to send E-mail messages to its recipients over the network.

The following figure shows the function of SMTP in the mail sending process:

Of course, just as there are multiple computer ports, there are many SMTP ports you can use.

2. SMTP Port

2.1 25

In 1982, USC submitted a proposal to the Internet Engineering Task Force (IETF), Request For Comments (RFC) 821, to establish port 25 as the default transport channel For Internet E-mail. Forty years later, you can still use port 25 to transfer mail between two mail servers.

However, security was not considered in the initial design, and in December 1998, R. Gellens and J. Klensin submitted RFC2476, in which the RFC proposed to separate the traditional concepts of message submission and message relay, The RFC defines that message submission should take place through port 587 (that is, port 587 should be used when we submit messages through tools such as mail clients) to ensure that new policies and security requirements do not interfere with traditional relay traffic on message relay port 25.

With this split, port 25 is primarily used for SMTP relays, which move mail from one E-mail server to another.

In most cases, SMTP email clients (Foxmail, Microsoft Outlook, Mail, Thunderbird, etc.) should not use port 25 to curb the amount of spam, so this port 25 is not relevant to our personal use.

2.2 587

This is the default mail submission port, which can be used when a user submits an email to a mail server, or when we send our own mail through Java code.

Port 587, combined with TLS encryption, ensures secure submission of email and adherence to guidelines laid down by the IETF.

2.3 465

So we’re supposed to use port 587 when we send emails. What’s 465 for?

The IETF has never published port 465 as an official SMTP transport or commit port, however IANA, which maintains much of the core Internet infrastructure, has assigned port 465 to SMTPS. The purpose is to establish a port for SMTP to operate using secure Sockets Layer (SSL), which makes mail delivery more secure.

465 is for SSL, 587 is for TLS. TLS (Transport Layer Security) is a more secure version of SSL. TLS is a product of SSL standardization.

In theory, 465 should be abolished and everyone uses 587. However, since 465 was once identified as valid by IANA, there may be legacy systems that can only use this port, so this port is not abandoned and can be used.

2.4 summary

Ok, so that’s the difference between these ports. In general, when sending emails using Spring Boot, both 465 and 587 will work, but 25 is not recommended. In addition, when using 465 or 587, some individual mailboxes such as mailbox 139 need to be configured with the following attributes:

spring.mail.properties.mail.smtp.ssl.enable=true
Copy the code

3. The extra

Maybe there are some friends who do not know how to send Spring Boot email, let’s review again.

Email is actually a very common requirement, user registration, find the place such as password, can use, use JavaSE code send mail, steps are tedious, Spring to send in the Boot, provides the related automation configuration class, make it very easy to find the email, then we have to find out! Take a look at five postures for sending mail using Spring Boot.

3.1 Email Basics

We often hear about various mail protocols, such as SMTP, POP3, IMAP, so what are the functions of these protocols, what are the differences? Let’s discuss this problem first.

SMTP is an application layer protocol based on TCP/IP. It is similar to HTTP. By default, the SMTP server listens to port 25. SMTP is an application layer protocol based on TCP/IP, so CAN I send an email through the Socket? The answer is yes.

In life, we go through the following steps to deliver an email:

  1. Xiao Wang in Shenzhen delivered the mail to the post office in Shenzhen first
  2. The post office in Shenzhen delivers mail to the post office in Shanghai
  3. Xiao Zhang from Shanghai comes to the post office to pick up his mail

This is a shortened version of life’s email process. These three steps can correspond to our mail delivery process, assuming that the mail is sent from [email protected] to [email protected]:

  1. [email protected] first delivers the mail to Tencent’s mail server
  2. Tencent’s mail server delivers our mail to NetEase’s mail server
  3. [email protected] Log in to the NetEase mail server to view emails

Mail delivery is basically this process, and this process involves multiple protocols, so let’s take a look at each of them.

SMTP is called Simple Mail Transfer Protocol. It defines the communication rules between Mail client software and SMTP server, as well as between SMTP server and SMTP server.

That is to say, [email protected] users use SMTP when they first send mail to Tencent’s SMTP server, and Tencent’s SMTP server uses SMTP when they send mail to NetEase’s SMTP server. The SMTP server is used to receive mail.

The POP3 Protocol is called Post Office Protocol. It defines the communication rules between mail clients and POP3 servers. In what scenarios is this Protocol used? When the mail arrives at NetEase’s SMTP server, [email protected] users need to log in to the server to check the mail. This protocol is used: Mail service providers provide special mail storage space for each user. After receiving the mail, the SMTP server saves the mail to the corresponding user’s mail storage space. To read the mail, the user needs to use the POP3 mail server of the mail service provider.

Finally, some of you may have heard of the IMAP protocol, which is an extension of the POP3 protocol with stronger functions and similar functions.

3.2 Preparations

At present, most domestic mail service providers are not allowed to directly use the user name/password to send emails in the code. They all need to apply for authorization code first. Here we take QQ mailbox as an example to demonstrate the application process of authorization code: First of all, we need to log in to QQ Mailbox webpage and click the Settings button above:

Then click on the Accounts TAB:

In the Accounts TAB, find the enable POP3/SMTP option as follows:

Click “Open” to enable the related functions. Mobile phone number verification is required during the enabling process. Follow the steps without further details. After this function is enabled successfully, you can obtain an authorization code and save the number for later use.

3.3 Project Creation

Next, we can create projects. Spring Boot provides automatic configuration classes for sending emails. Developers only need to add relevant dependencies and configure the basic information of the mailbox to send emails.

  • Start by creating a Spring Boot project that introduces a mail sending dependency:

After creation, the project dependencies are as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code
  • Configure basic mailbox information

After the project is successfully created, configure the basic information for the mailbox in application.properties:

spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=[email protected]
spring.mail.password=ubknfzhjkhrbbabe
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
Copy the code

The configuration meanings are as follows:

  • The SMTP server address is specified
  • Port number of the SMTP server
  • The email user name is specified
  • Configure the password, note that it is not the real password, but the authorization code just obtained
  • The default message code
  • Accessories SSL encryption factory
  • Indicates that the DEBUG mode is enabled. In this way, mail sending logs are displayed on the console for troubleshooting

If you do not know the SMTP server port or address, you can refer to the Tencent mailbox document

  • Service.mail.qq.com/cgi-bin/hel…

After I finish these, Spring Boot automatically configured for us mail class, related configuration in the org. Springframework. Boot. Autoconfigure. Mail. MailSenderAutoConfiguration class, Part of the source code is as follows:

@Configuration
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class)
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
public class MailSenderAutoConfiguration {}Copy the code

From this code, you can see, another configuration MailSenderPropertiesConfiguration imports the class, the class, the class provides email related tools:

@Configuration
@ConditionalOnProperty(prefix = "spring.mail", name = "host")
class MailSenderPropertiesConfiguration {
        private final MailProperties properties;
        MailSenderPropertiesConfiguration(MailProperties properties) {
                this.properties = properties;
        }
        @Bean
        @ConditionalOnMissingBean
        public JavaMailSenderImpl mailSender(a) {
                JavaMailSenderImpl sender = new JavaMailSenderImpl();
                applyProperties(sender);
                returnsender; }}Copy the code

As you can see, an instance of JavaMailSenderImpl has been created, JavaMailSenderImpl is an implementation of JavaMailSender, which we will use to send the message.

After the above two steps are done, the preparation for sending the email is complete. Then you can send the email directly.

There are five different ways to send, and we’ll look at them one by one.

3.3.1 Sending a Simple Email

A simple email is a plain text document:

@Autowired
JavaMailSender javaMailSender;
@Test
public void sendSimpleMail(a) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setSubject("This is a test email.");
    message.setFrom("[email protected]");
    message.setTo("[email protected]");
    message.setCc("[email protected]");
    message.setBcc("[email protected]");
    message.setSentDate(new Date());
    message.setText("This is the body of the test email.");
    javaMailSender.send(message);
}
Copy the code

From top to bottom, the code meanings are as follows:

  1. Build a mail object
  2. Setting email Subject
  3. Set the sender of the message
  4. Set email recipients. You can have multiple recipients
  5. Set the email cc person, can have more than one cc person
  6. Set up a secret cc person, you can have more than one
  7. Set the email sending date
  8. Set the email body
  9. Send E-mail

Finally, the method is executed to realize the sending of emails. The sending effect picture is as follows:

3.3.2 Sending emails with Attachments

Email attachments can be pictures or ordinary files, both of which are supported.

@Test
public void sendAttachFileMail(a) throws MessagingException {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
    helper.setSubject("This is a test email.");
    helper.setFrom("[email protected]");
    helper.setTo("[email protected]");
    helper.setCc("[email protected]");
    helper.setBcc("[email protected]");
    helper.setSentDate(new Date());
    helper.setText("This is the body of the test email.");
    helper.addAttachment("javaboy.jpg".new File("C:\\Users\\sang\\Downloads\\javaboy.png"));
    javaMailSender.send(mimeMessage);
}
Copy the code

Note that there is a difference between building a mail object and the previous one. Here, we get a complex mail object from javaMailSender and configure the mail using MimeMessageHelper, which is a mail configuration helper class. The creation of true indicates that a message of type multipart message is constructed. With MimeMessageHelper, the configuration of the message is done by MimeMessageHelper.

Finally add an attachment via the Addattplunge method.

After this method is executed, the email sending effect picture is as follows:

3.3.3 Sending An Email With Picture Resources

What’s the difference between an image resource and an attachment? Image resources are placed in the body of the message, that is, when you open the message, you can see the image. However, in general, this method is not recommended, and some companies have a limit on the size of the content (because it is sent together with images).

@Test
public void sendImgResMail(a) throws MessagingException {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setSubject("This is a test email.");
    helper.setFrom("[email protected]");
    helper.setTo("[email protected]");
    helper.setCc("[email protected]");
    helper.setBcc("[email protected]");
    helper.setSentDate(new Date());
    helper.setText(

"

.true); helper.addInline("p01".new FileSystemResource(new File("C:\\Users\\sang\\Downloads\\javaboy.png"))); helper.addInline("p02".new FileSystemResource(new File("C:\\Users\\sang\\Downloads\\javaboy2.png"))); javaMailSender.send(mimeMessage); } Copy the code

The message text is an HTML text, and the image resource is represented by a placeholder. The second parameter to setText is true, which indicates that the first parameter is an HTML text.

After setText, add the image resource by using the addInline method.

Finally, execute the method to send an email, the effect is as follows:

In actual company development, neither the first nor the third mail delivery schemes are the most used. Generally speaking, the content of emails is relatively rich, so most of the emails are presented by HTML. If THE HTML string is directly concatenated, it will be difficult to maintain in the future. In order to solve this problem, there will be corresponding email templates for sending emails. The two most representative templates are the Freemarker template and the Thyemeleaf template.

3.3.4 Use Freemarker as a mail template

First we need to introduce a Freemarker dependency:

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

Then create a mail.ftl in the Resources/Templates directory as a template for sending mail:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>Welcome to join XXX family, your entry information is as follows:</p>
<table border="1">
    <tr>
        <td>The name</td>
        <td>${username}</td>
    </tr>
    <tr>
        <td>Work number</td>
        <td>${num}</td>
    </tr>
    <tr>
        <td>salary</td>
        <td>${salary}</td>
    </tr>
</table>
<div style="color: #ff1a0e">Work together to create brilliance</div>
</body>
</html>
Copy the code

Next, render the mail template into HTML and send it.

@Test
public void sendFreemarkerMail(a) throws MessagingException, IOException, TemplateException {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setSubject("This is a test email.");
    helper.setFrom("[email protected]");
    helper.setTo("[email protected]");
    helper.setCc("[email protected]");
    helper.setBcc("[email protected]");
    helper.setSentDate(new Date());
    // Build Freemarker's basic configuration
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
    // Configure the template location
    ClassLoader loader = MailApplication.class.getClassLoader();
    configuration.setClassLoaderForTemplateLoading(loader, "templates");
    // Load the template
    Template template = configuration.getTemplate("mail.ftl");
    User user = new User();
    user.setUsername("javaboy");
    user.setNum(1);
    user.setSalary((double) 99999);
    StringWriter out = new StringWriter();
    // Render the template, the result of rendering will be saved in out, send the HTML string in out
    template.process(user, out);
    helper.setText(out.toString(),true);
    javaMailSender.send(mimeMessage);
}
Copy the code

Note that although the automatic Configuration of Freemarker has been introduced, we reconfigure Freemarker directly with the new Configuration, so the default Configuration of Freemarker does not take effect here. Therefore, when filling in the template location, The value of templates.

Call this method, send an email, the effect picture is as follows:

3.3.5 Using Thymeleaf as the Mail template

It is recommended to use Thymeleaf in Spring Boot to build mail templates. Because Thymeleaf’s automated configuration provides a TemplateEngine that makes it easy to render Thymeleaf templates into HTML, Thymeleaf’s automated configuration is still valid here.

First, introduce the Thymeleaf dependency:

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

Then, create the Thymeleaf mail template:

<! DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>Welcome to join XXX family, your entry information is as follows:</p>
<table border="1">
    <tr>
        <td>The name</td>
        <td th:text="${username}"></td>
    </tr>
    <tr>
        <td>Work number</td>
        <td th:text="${num}"></td>
    </tr>
    <tr>
        <td>salary</td>
        <td th:text="${salary}"></td>
    </tr>
</table>
<div style="color: #ff1a0e">Work together to create brilliance</div>
</body>
</html>
Copy the code

Next email:

@Autowired
TemplateEngine templateEngine;

@Test
public void sendThymeleafMail(a) throws MessagingException {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setSubject("This is a test email.");
    helper.setFrom("[email protected]");
    helper.setTo("[email protected]");
    helper.setCc("[email protected]");
    helper.setBcc("[email protected]");
    helper.setSentDate(new Date());
    Context context = new Context();
    context.setVariable("username"."javaboy");
    context.setVariable("num"."000001");
    context.setVariable("salary"."99999");
    String process = templateEngine.process("mail.html", context);
    helper.setText(process,true);
    javaMailSender.send(mimeMessage);
}
Copy the code

Call this method, send an email, the effect picture is as follows:

Ok, so those are the five email postures we talked about today. Have you mastered them?

This example has been uploaded to GitHub: github.com/lenve/javab… .

If you have any questions, please leave a comment.

References:

  • www.mailgun.com/blog/which-…