introduce
E-mail service is one of the common services with many functions. It can send activities and marketing advertisements to users externally, and send system monitoring reports and alarms internally.
This article will introduce how spring boot integrates the mail service and give the configuration of different mail service providers.
As shown in the figure:
development process
Spring boot building
The construction of Springboot is very simple. We use Spring Initializr It's very convenient to build. You can quickly complete the project by selecting the modules you need:
Introducing dependency
In order to use the mail service, we need to introduce related dependencies. For spring boot, add the following dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
configuration file
You need to configure the parameters of the mail service provider, such as service address, user name and password. The following example is the configuration of QQ. The password is not the QQ password, but the QQ authorization code. We will talk about how to obtain it later.
The configuration file application.yml of Springboot is as follows:
server: port: 8080 spring: profiles: active: qq --- spring: profiles: qq mail: host: smtp.qq.com username: xxx@qq.com password: xxx properties: mail: smtp: auth: true starttls: enable: true required: true --- spring: profiles: netEase mail: host: smtp.163.com username: xxx@163.com password: xxx properties: mail: smtp: auth: true starttls: enable: true required: true
Implementation of sending service
After JavaMailSender is injected and Message is assembled, you can send the simplest text mail.
@Autowired private JavaMailSender emailSender; public void sendNormalText(String from, String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(text); emailSender.send(message); }
Calling interface
After the service call is implemented, the REST interface is exposed through the Controller. The specific code is as follows:
@Value("${spring.mail.username}") private String username; @Autowired private MailService mailService; @GetMapping("/normalText") public Mono<String> sendNormalText() { mailService.sendNormalText(username, username, "Springboot Mail(Normal Text)", "This is a mail from Springboot!"); return Mono.just("sent"); }
Inject the implemented MailService into the Controller and call the corresponding method. The sender and receiver of this email are the same account, which can be flexibly configured in practice.
Use the Postman call interface to test whether the following can be sent normally:
Successfully returned "sent" and received an email. The test passed.
Multiple types of mail
Simple text mail
How to send a simple text email has just been explained and will not be explained in detail.
HTML mail
Although plain text has been able to meet many needs, but many times also need more rich styles to improve the performance of the mail. HTML type mail is very useful.
The Service code is as follows:
public void sendHtml(String from, String to, String subject, String text) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); emailSender.send(message); }
Different from simple text, this time we use MimeMessage and MimeMessageHelper, which are very useful classes. We will often use them later, and the combination of them can greatly enrich the mail representation.
The code of the Controller is as follows:
@GetMapping("/html") public Mono<String> sendHtml() throws MessagingException { mailService.sendHtml(username, username, "Springboot Mail(HTML)", "<h1>This is a mail from Springboot!</h1>"); return Mono.just("sent"); }
Mail with attachments
It is normal to send a message file. However, to send an attachment, you need to use the MimeMessageHelper.addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) method. The first parameter is the attachment name, and the second parameter is the file stream resource. The Service code is as follows:
public void sendAttachment(String from, String to, String subject, String text, String filePath) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource file = new FileSystemResource(new File(filePath)); helper.addAttachment(filePath, file); emailSender.send(message); }
The Controller code is as follows:
@GetMapping("/attachment") public Mono<String> sendAttachment() throws MessagingException { mailService.sendAttachment(username, username, "Springboot Mail(Attachment)", "<h1>Please check the attachment!</h1>", "/Pictures/postman.png"); return Mono.just("sent"); }
Mail with static resources
The webpage we visit is also an HTML, which can bring many static resources, such as pictures, videos, etc. The Service code is as follows:
public void sendStaticResource(String from, String to, String subject, String text, String filePath, String contentId) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource file = new FileSystemResource(new File(filePath)); helper.addInline(contentId, file); emailSender.send(message); }
Among them, contentId is the ID of the static resource in HTML, which needs to be mapped.
The Controller code is as follows:
@GetMapping("/inlinePicture") public Mono<String> sendStaticResource() throws MessagingException { mailService.sendStaticResource(username, username, "Springboot Mail(Static Resource)", "<html><body>With inline picture<img src='cid:picture' /></body></html>", "/Pictures/postman.png", "picture"); return Mono.just("sent"); }
Template mail
There are many template engines in Java, such as Freemarker, Thymeleaf, Velocity, etc., which are not the focus of this point, so we only use Freemarker as an example.
The Service code is as follows:
@Autowired private FreeMarkerConfigurer freeMarkerConfigurer; public void sendTemplateFreemarker(String from, String to, String subject, Map<String, Object> model, String templateFile) throws Exception { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateFile); String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); helper.setText(html, true); emailSender.send(message); }
Note that you need to inject FreeMarkerConfigurer, then use FreeMarkerTemplateUtils to parse the template and return String, which can be sent as content.
The Controller code is as follows:
@GetMapping("/template") public Mono<String> sendTemplateFreemarker() throws Exception { Map<String, Object> model = new HashMap<>(); model.put("username", username); model.put("templateType", "Freemarker"); mailService.sendTemplateFreemarker(username, username, "Springboot Mail(Template)", model, "template.html"); return Mono.just("sent"); }
Note that the template file template.html should be placed under the resources/templates / directory so that it can be found.
The template content is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello ${username}</h1> <h1>This is a mail from Springboot using ${templateType}</h1> </body> </html>
Where ${username} and ${templateType} are variable names to be replaced, Freemarker provides many rich variable expressions, which will not be expanded here.
Integrate different mail service providers
There are many email service providers. The most commonly used ones in China are QQ mailbox and Netease 163 mailbox.
Integrated QQ email requires a necessary account and an authorization code. After the authorization code is opened, it can be used after configuration. The official documents are as follows:
What is the authorization code and how is it set?
It should be noted that to activate the authorization code, you need to use the bound mobile phone number to send SMS to a specific number. If there is no binding mobile phone or the binding mobile phone is not available, it will affect the activation.
After opening, the authorization code should be configured into the file as a password.
163
There is not much difference between the way of opening Netease and QQ. For specific guidance, please refer to the following official documents:
How to open the client authorization code?
It is also necessary to bind the mobile phone for operation.
summary
The email received after sending this example is shown as follows:
E-mail is powerful, and spring boot is also very easy to integrate. Technology is a sharp tool, which can be used well without abuse.
Welcome to the public account "pumpkin slow talk", it will keep updating for you...
This article is based on the platform of blog one article multiple sending OpenWrite Release!