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, in this paper, we have to find out! Take a look at five postures for sending mail using Spring Boot.
Email based
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:
- Xiao Wang in Shenzhen delivered the mail to the post office in Shenzhen first
- The post office in Shenzhen delivers mail to the post office in Shanghai
- 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]:
- [email protected] first delivers the mail to Tencent’s mail server
- Tencent’s mail server delivers our mail to netease’s mail server
- [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.
The preparatory work
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.
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
[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.
Send 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:
- Build a mail object
- Setting email Subject
- Set the sender of the message
- Set email recipients. You can have multiple recipients
- Set the email cc person, can have more than one cc person
- Set up a secret cc person, you can have more than one
- Set the email sending date
- Set the email body
- Send E-mail
Finally, the method is executed to realize the sending of emails. The sending effect picture is as follows:
Send a message 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:
Send a message with an image resource
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.
Use Freemarker as the 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:
<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:
Use 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:
<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.
Pay attention to the public account [Jiangnan little Rain], focus on Spring Boot+ micro service and front and back end separation and other full stack technology, regular video tutorial sharing, after attention to reply to Java, get Songko for you carefully prepared Java dry goods!