1. Introduction
Sending emails should be one of the essential features of the website, such as registration verification, forgetting your password or sending marketing messages to users. In the early days, we would use JavaMail-related APIs to write relevant code for sending emails. Later, spring exited JavaMailSender and simplified the process of sending emails. After that, springboot encapsulated this and then it has the current spring-boot-starter-mail. The introduction of this article mainly comes from this package.
2. Simple use
1. Pom package configuration
Add spring-boot-starter-mail package reference to the pom package
<dependencies> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies>
2. Add mailbox configuration in
=smtp.1234. //Email Server Address=5678@ //username=09876 //password-encoding=UTF-8 =65432@ //Who will send the email
3. Write mailService, only implementation classes are proposed here.
@Component public class MailServiceImpl implements MailService{ private final Logger logger = (()); @Autowired private JavaMailSender mailSender; @Value("${}") private String from; @Override public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); (from); (to); (subject); (content); try { (message); ("Simple email has been sent."); } catch (Exception e) { ("Exception occurred while sending a simple email!", e); } } }
4. Write test class for testing
@RunWith() @SpringBootTest public class MailServiceTest { @Autowired private MailService MailService; @Test public void testSimpleMail() throws Exception { ("123456w@","test simple mail"," hello this is simple mail"); } }
At this point, a simple text sending is complete.
3. Add some materials
However, during normal use, we usually add pictures or attachments to the email to enrich the content of the email. The following is how to use springboot to send rich emails.
3. Send html format email
The other way is not changed to add the sendHtmlMail method in MailService.
public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = (); try { //true means that you need to create a multipart messageMimeMessageHelper helper = new MimeMessageHelper(message, true); (from); (to); (subject); (content, true); (message); ("html mail sent successfully"); } catch (MessagingException e) { ("Exception occurred while sending html mail!", e); } }
Build html content in the test class, and test send:
@Test public void testHtmlMail() throws Exception { String content="<html>\n" + "<body>\n" + " <h3>hello world ! This is an Html email!</h3>\n" + "</body>\n" + "</html>"; ("ityouknow@","test simple mail",content); }
3. Send emails with attachments
Add the sendAttachmentsMail method in MailService.
public void sendAttachmentsMail(String to, String subject, String content, String filePath){ MimeMessage message = (); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); (from); (to); (subject); (content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = (()); (fileName, file); (message); ("The email with attachment has been sent."); } catch (MessagingException e) { ("Exception occurred while sending an email with attachment!", e); } }
Adding multiple attachments can use multiple (fileName, file)
4. Add test methods to the test class
@Test public void sendAttachmentsMail() { String filePath="e:\\tmp\\"; ("ityouknow@", "Subject: Email with attachments", "If there are attachments, please check them!", filePath); }
5. Send emails with static resources
Static resources in emails generally refer to images. Add the sendAttachmentsMail method to MailService.
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){ MimeMessage message = (); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); (from); (to); (subject); (content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); (rscId, res); (message); ("The mail embedded in the static resource has been sent."); } catch (MessagingException e) { ("Exception occurred while sending emails embedded with static resources!", e); } }
Add test methods to the test class:
@Test public void sendInlineResourceMail() { String rscId = "12345"; String content="<html><body>This is an email with pictures:<img src=\'cid:" + rscId + "\' ></body></html>"; String imgPath = "C:\\Users\\summer\\Pictures\\"; ("ityouknow@", "Subject: This is an email with pictures", content, imgPath, rscId); }
Adding multiple images can be achieved using multiple <img src='cid:" + rscId + "' > and (rscId, res)
All email sending services have been completed here.
Email system:
These are the basic services for sending emails above, but if we want to build a mail system, we still need to consider the following issues:
Email Template:
We often receive emails like this:
Dear neo users:
Congratulations on registering as a user of xxx.com. Thank you for your attention and support for xxx and welcome you to use xx's products and services.
...
Among them, only the username neo is changing, and the content of other emails remains unchanged. If you need to manually splice each email, it will not be elegant enough. It is also inconvenient to modify the code every time the template is modified. Therefore, it is recommended to make an email template to handle this type of email needs. The essence of a template is very simple. It is to replace the changed parameters in the template and convert them into an html string. Here we use thymeleaf as an example to demonstrate.
4. Import thymeleaf package in pom
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
5. Create under resources/templates
<!DOCTYPE html> <html lang="zh" xmlns:th=""> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> Hello,This is a verification email,Please click the link below to complete the verification, <a href="#" rel="external nofollow" th:href="@{ http:///neo/{id}(id=${id}) }" rel="external nofollow" >Activate the account</a></body> </html>
6. Analyze the template and send it
@Test public void sendTemplateMail() { //Create email textContext context = new Context(); ("id", "006"); String emailContent = ("emailTemplate", context); ("ityouknow@","Subject: This is a template email",emailContent); }
1. Send failed
Due to various reasons, there will always be cases where emails are sent, such as: emails are sent too frequently, network abnormalities, etc. When this happens, we generally consider retrying the email, which will be divided into the following steps:
- 1. When receiving the sending email request, first record the request and enter the database.
- 2. Call the email sending interface to send emails, and record the sending results into the library.
- 3. During the scanning time period of the startup time system, emails that have not been sent successfully and retryed less than 3 times will be sent again.
7. Asynchronous sending
Many times, email sending is not a result that our main business must pay attention to. For example, notification and reminder businesses can allow delays or failures. At this time, you can use asynchronous methods to speed up the execution of the main transaction. In actual projects, you can use MQ to send emails and start sending emails after listening to the message queue.
This is the end of this article about the details of SpringBoot Mail email tasks. For more related SpringBoot Mail content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!