preface
The function of email sending is very common in actual projects. Many operations such as user forgetting account and password are interactive through email. Therefore, email sending is an essential function module in Web development.
This article appeared on my personal blog: [www.xiongfrblog.cn]
Configuration procedure in Spring Boot
Spring itself provides useful org. Springframework. Mail. Javamail. JavaMailSender interface to implement the email function, Spring also provides automation configuration in the boot, so we use rise very convenient.
Add the dependent
First, add the following dependencies to the pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Copy the code
Modifying a Configuration File
After adding dependencies, you need to configure the parameters related to sending emails in the project configuration file application.properties, as follows:
spring.mail.host=smtp.163.com
spring.mail.username=xxx
spring.mail.password=xxx
spring.mail.default-encoding=UTF-8
Copy the code
These are the important parameters, use the default values for the rest. Here’s how:
spring.mail.host
: Email server address, this depends on what email you use, such as:smtp.163.com
: 163 mailboxsmtp.126.com
: 126 mailboxsmtp.qq.com
: qq email
spring.mail.username
: Mailbox Login user name.spring.mail.password
: Third-party login authorization code (how to obtain the authorization code is described below).spring.mail.default-encoding
: Coding mode
POP3/SMTP
service
The concept of authorization code has been mentioned above. First of all, we should make it clear that the authorization code is not the same as the password for us to log in to the mailbox directly. The authorization code can be understood as the password for the third-party client to log in to the mailbox. Here I will take my account 163 as an example to introduce the steps of opening the service and obtaining the authorization code, as shown in the figure below:
Log in to the official website of email 163 and follow the steps shown in the figure. After selecting the service, the verification code will be sent to you. After entering the verification code, you will be allowed to set the authorization code.
Encapsulate mail tool class
The best way to do this is to encapsulate a class for code reuse and maintenance, which I encapsulate here as a Service layer.
Define interface imailService. interface:
package com.web.springbootmail.service;
/ * * *@author Promise
* @createTimeMarch 30, 2019 3:14:14 *@description* /
public interface IMailService {
/** * Simple text mail *@paramToUser Mail recipient */
void simpleMil(String toUser)throws Exception;
/** * HTML mail *@paramToUser Mail recipient */
void htmlMail(String toUser) throws Exception;
/** * Mail with attachment *@paramToUser Mail recipient */
void attachmentMail(String toUser)throws Exception;
/** * Email with pictures *@paramToUser Mail recipient */
void imgMail(String toUser)throws Exception;
/** * template mail *@paramToUser Mail recipient */
void TemplateMail(String toUser)throws Exception;
}
Copy the code
The implementation class MailServiceimpl. Java:
package com.web.springbootmail.service.impl;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
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 org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import com.web.springbootmail.service.IMailService;
/ * * *@author Promise
* @createTimeMarch 30, 2019 3:14:37 *@descriptionMail sending service */
@Service("mailService")
public class MailServiceImpl implements IMailService{
@Autowired
private JavaMailSender jms;
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String from;
@Override
public void simpleMil(String toUser) {}@Override
public void htmlMail(String toUser) {
// TODO Auto-generated method stub
}
@Override
public void attachmentMail(String toUser) {
// TODO Auto-generated method stub
}
@Override
public void imgMail(String toUser) {
// TODO Auto-generated method stub
}
@Override
public void TemplateMail(String toUser) {
// TODO Auto-generated method stub}}Copy the code
Only the framework is given here, the concrete implementation is described in turn, and three variables are injected above:
jms
: Indicates the email sending interfacetemplateEngine
: parses the template when sending a template emailfrom
: Reads the account of the mail sender configured in the configuration file
The implementation of each type of mail is described below
Simple text mail
This class of mail is the simplest, using the SimpleMailMessage object. The code looks like this:
@Override
public void simpleMil(String toUser) {
// TODO Auto-generated method stub
// Initialize the simple mail object
SimpleMailMessage message = new SimpleMailMessage();
// The sender of the email
message.setFrom(from);
// Mail receiver
message.setTo(toUser);
// The subject of the message
message.setSubject("Simple mail");
// Email content
message.setText("Simple Content");
// Send mail
jms.send(message);
}
Copy the code
HTML email
This class of mail uses the MimeMessage object to enrich the page style, as follows:
@Override
public void htmlMail(String toUser) throws MessagingException {
// TODO Auto-generated method stub
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toUser);
helper.setSubject("HTML Mail");
// The content is in HTML format
String content = " This is an HTML file
This is an HTML file
";
// True: sends the email in HTML format
helper.setText(content, true);
jms.send(message);
}
Copy the code
Mail with an attachment
MimeMessage is also used. The code is as follows:
@Override
public void attachmentMail(String toUser) throws MessagingException {
// TODO Auto-generated method stub
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toUser);
helper.setSubject("Mail with Attachments");
// Load the absolute path resource
FileSystemResource fs = new FileSystemResource(new File("D:\\DownLoad\\file\\ Alibaba Java Development Manual v1.2.0.pdf"));
helper.setText("This is an email with an attachment!");
// Add attachment resources
helper.addAttachment("Alibaba Java Development Manual v1.2.0.pdf", fs);
jms.send(message);
}
Copy the code
The file path here is the absolute path of the local file.
Mail with pictures
The code is as follows:
@Override
public void imgMail(String toUser) throws MessagingException {
// TODO Auto-generated method stub
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toUser);
helper.setSubject("Mail with pictures");
// Set the CID of the resource
String content = "< HTML > < body > blog picture < img SRC = 'cid: img' / > < / body > < / HTML >";
helper.setText(content, true);
FileSystemResource fs = new FileSystemResource(new File("D:\\DownLoad\\img\\20171123181522_c48800.jpg"));
// Select cid from cid
helper.addInline("img", fs);
jms.send(message);
}
Copy the code
In fact, this way is also HTML mail, but more static resources, for example, here we add a picture on the page, the steps are similar to adding an attachment, but it should be noted that static resources need to set cid for static resources, so that there are multiple static resources to distinguish.
Template mail
Template mail means that the body content of the mail is the same, only some parts are different, so we can define a template of the mail, when sending the mail we directly pass in the parameters can be, is a good encapsulation.
The template parsing framework I’m using here is Thymeleaf, so I need to add dependencies to the project pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Copy the code
Next in the SRC/main/resources/templates directory MailTemplate. The new HTML files, content is as follows:
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>How do you do?<span th:text="${username}"></span>: This is the email template from the test!</h2>
</body>
</html>
Copy the code
Use specific code as follows:
@Override
public void TemplateMail(String toUser) throws MessagingException {
// TODO Auto-generated method stub
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toUser);
helper.setSubject("Template Mail");
Context context = new Context();
// Pass parameters to the template. The username should be the same as the variable name in the template, and promise should be the test data
context.setVariable("username"."promise");
/ / thymeleaf template will default from the SRC/main/resources/tempaltes directory for the file, fill in the us to define the template name, do not need to write the suffix.
String template = templateEngine.process("MailTemplate", context);
helper.setText(template, true);
jms.send(message);
}
Copy the code
The controller calls
After encapsulating the email sending utility class, we can call it directly in controller as follows:
package com.web.springbootmail.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.web.springbootmail.service.IMailService;
/ * * *@author Promise
* @createTimeApril 1, 2019 at 9:30:38 PM *@descriptionEmail sending */
@RequestMapping("/mail")
@RestController
public class EmailController {
@Autowired
private IMailService mailService;
@GetMapping("/simple")
public Map<String, Object> sendSimpleMail(a) {
Map<String, Object> map =new HashMap<>();
try {
// The parameter is the mailbox to receive the mail
mailService.simpleMil("*****@qq.com");
map.put("res"."success");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
map.put("res"."error");
}
return map;
}
@GetMapping("/htmlMail")
public Map<String, Object> htmlMail(a){
Map<String, Object> map =new HashMap<>();
try {
mailService.htmlMail("*****@qq.com");
map.put("res"."success");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
map.put("res"."error");
}
return map;
}
@GetMapping("/attachmentsMail")
public Map<String, Object> attachmentsMail(a){
Map<String, Object> map =new HashMap<>();
try {
mailService.attachmentMail("*****@qq.com");
map.put("res"."success");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
map.put("res"."error");
}
return map;
}
@GetMapping("/imgMail")
public Map<String, Object> imgMail(a){
Map<String, Object> map =new HashMap<>();
try {
mailService.imgMail("*****@qq.com");
map.put("res"."success");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
map.put("res"."error");
}
return map;
}
@GetMapping("/templateMail")
public Map<String, Object> templateMail(a){
Map<String, Object> map =new HashMap<>();
try {
mailService.TemplateMail("*****@qq.com");
map.put("res"."success");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
map.put("res"."error");
}
returnmap; }}Copy the code
Effect of the test
Simple Email Effect
Start the project, access localhost: 8080 / mail/simple, my inbox at this time received the following email:
HTML email
Access localhost: 8080 / mail/htmlMail, the effect is as follows:
Attached mail
Access localhost: 8080 / mail/attachmentsMail, the effect is as follows:
Mail with pictures
Access localhost: 8080 / mail/imgMail, the effect is as follows:
Template mail
Access localhost: 8080 / mail/templateMail, the effect is as follows:
conclusion
Well, that’s it for Spring Boot. Thanks for reading