Springboot-email service,

Source: Internet
Author: User

Springboot-email service,

Springboot is still developing at a high speed, but it has not been noticed for more than five months. Now we see that the official website has reached version 1.5.3.RELEASE. Prepare to write springboot-related articles. This article uses springboot's latest version 1.5.3 for development.

Sending emails should be one of the essential functions of the website, such as registration verification, password forgotten, or marketing information sent to users. In the early stage, we used JavaMail APIs to write the code for sending emails. Later, spring exited JavaMailSender, which simplifies the mail sending process, springboot then encapsulates the current spring-boot-starter-mail package. The introduction in this chapter mainly comes from this package.

Simple use 1. pom package Configuration

Add spring-boot-starter-mail package reference in the pom package

1.   <dependencies>2.       <dependency> 3.           <groupId>org.springframework.boot</groupId>4.           <artifactId>spring-boot-starter-mail</artifactId>5.       </dependency> 6.   </dependencies>
2. Add mailbox configuration in application. properties
1. spring. mail. host = smtp.qiye.163.com // email server address 2. spring. mail. username = xxx@oo.com // username 3. spring. mail. password = xxyyooo // password 4. spring. mail. default-encoding = UTF-85. 6. mail. fromMail. addr = xxx@oo.com // who will send the email
3. Compile mailService. Here we only propose the implementation class.
1. @ Component2. public class MailServiceImpl implements MailService {3. 4. private final Logger logger = LoggerFactory. getLogger (this. getClass (); 5. 6. @ Autowired7. private JavaMailSender mailSender; 8. 9. @ Value ("$ {mail. fromMail. addr} ") 10. private String from; 11. 12. @ Override13. public void sendSimpleMail (String to, String subject, String content) {14. simpleMailMessage message = new SimpleMailMess Age (); 15. message. setFrom (from); 16. message. setTo (to); 17. message. setSubject (subject); 18. message. setText (content); 19. 20. try {21. mailSender. send (message); 22. logger.info ("A simple email has been sent. "); 23.} catch (Exception e) {24. logger. error (" an Exception occurred when sending a simple email! ", E); 25.} 26. 27.} 28 .}
4. Write the test class for testing.
1.   @RunWith(SpringRunner.class)2.   @SpringBootTest3.   public class MailServiceTest {4.    5.       @Autowired6.       private MailService MailService;7.    8.       @Test9.       public void testSimpleMail() throws Exception {10.          MailService.sendSimpleMail("ityouknow@126.com","test simple mail"," hello this is simple mail");11.      }12.  }

Now a simple text is sent.

Add Materials

However, during normal use, we usually add images or attachments to emails to enrich the content of emails. The following describes how to use springboot to send rich emails.

Send html emails

Add the sendHtmlMail method in MailService.

1. public void sendHtmlMail (String to, String subject, String content) {2. mimeMessage message = mailSender. createMimeMessage (); 3. 4. try {5. // true indicates that a multipart message6. MimeMessageHelper helper = new MimeMessageHelper (message, true); 7. helper. setFrom (from); 8. helper. setTo (to); 9. helper. setSubject (subject); 10. helper. setText (content, true); 11. 12. mailSender. send (message); 13. logger.info ("htm L The email is successfully sent "); 14.} catch (MessagingException e) {15. logger. error (" an exception occurred when sending an html email! ", E); 16.} 17 .}

Construct html content in the test class and test sending

1. @ Test2. public void testHtmlMail () throws Exception {3. string content = "Send email with attachment

Add the sendAttachmentsMail method to MailService.

1. public void sendAttachmentsMail (String to, String subject, String content, String filePath) {2. mimeMessage message = mailSender. createMimeMessage (); 3. 4. try {5. mimeMessageHelper helper = new MimeMessageHelper (message, true); 6. helper. setFrom (from); 7. helper. setTo (to); 8. helper. setSubject (subject); 9. helper. setText (content, true); 10. 11. fileSystemResource file = new FileSystemResource (new File (FilePath); 12. string fileName = filePath. substring (filePath. lastIndexOf (File. separator); 13. helper. addAttachment (fileName, file); 14. 15. mailSender. send (message); 16. logger.info ("emails with attachments have been sent. "); 17.} catch (MessagingException e) {18. logger. error (" an exception occurred when sending an email with an attachment! ", E); 19.} 20 .}

Multiple attachments can be added.helper.addAttachment(fileName,file)

Add a test method to the test class

1. @ Test2. public void sendAttachmentsMail () {3. string filePath = "e: \ tmp \ application. log "; 4. mailService. sendAttachmentsMail ("ityouknow@126.com", "Subject: email with attachment", "Attachment available, please check! ", FilePath); 5 .}
Send emails with static Resources

A static resource in a mail is generally an image. The sendAttachmentsMail method is added to the MailService.

1. public void sendInlineResourceMail (String to, String subject, String content, String rscPath, String rscId) {2. mimeMessage message = mailSender. createMimeMessage (); 3. 4. try {5. mimeMessageHelper helper = new MimeMessageHelper (message, true); 6. helper. setFrom (from); 7. helper. setTo (to); 8. helper. setSubject (subject); 9. helper. setText (content, true); 10. 11. fileSystemResource res = new FileSystemRe Source (new File (rscPath); 12. helper. addInline (rscId, res); 13. 14. mailSender. send (message); 15. logger.info ("emails embedded with static resources have been sent. "); 16.} catch (MessagingException e) {17. logger. error (" an exception occurred when sending an email embedded with static resources! ", E); 18.} 19 .}

Add a test method to the test class

1. @ Test2. public void sendInlineResourceMail () {3. string rscId = "neo006"; 4. string content = "

You can add multiple images andhelper.addInline(rscId,res)To achieve

All email sending services have been completed.

Email System

This is the basic service for sending emails, but if we want to build an email system, we need to consider the following:

Email template

We often receive such Emails:

1. Dear neo User:. Congratulations, you have registered as a user of xxx network, and thank you for your attention and support for xxx. You are welcome to use xx products and services. 4 ....

Only the user name of neo is changing, and the content of other emails remains unchanged. It is not elegant if you need to manually splice all emails to send, in addition, it is inconvenient to modify the code for every template modification. Therefore, we recommend that you make an email template for such mail requirements. The nature of the template is very simple. It is to replace the changed parameters in the template and convert them into html strings. Here we usethymeleafFor example.

1. Import the thymeleaf package to pom

1.   <dependency>2.       <groupId>org.springframework.boot</groupId>3.       <artifactId>spring-boot-starter-thymeleaf</artifactId>4.   </dependency>

2. Create emailtemplate.html under resorces/templates

1. <! DOCTYPE html> 2. 

3. parse the template and send it

1. @ Test2. public void sendTemplateMail () {3. // create the mail body 4. context context = new Context (); 5. context. setVariable ("id", "006"); 6. string emailContent = templateEngine. process ("emailTemplate", context); 7. 8. mailService. sendHtmlMail ("ityouknow@126.com", "Subject: This is template mail", emailContent); 9 .}
Failed to send

For various reasons, there will always be situations where the email fails to be sent, for example, the email is sent too frequently or the network is abnormal. In this case, we generally consider re-sending the email. The steps are as follows:

  • 1. When an email request is received, the request is first recorded and stored in the database.

  • 2. Call the mail sending interface to send the mail, and record the sending result to the database.

  • 3. During the scheduled system scan period, emails that fail to be sent and the number of retries is less than three are sent again.

Asynchronous transmission

In many cases, email sending is not the result that must be followed by our main business. For example, notification and reminder services can allow latency or failure. In this case, you can send emails asynchronously to speed up the execution of the main transaction. In actual projects, you can use MQ to send email-related parameters, and start sending emails after listening to the message queue.

Sample Code: https://github.com/ityouknow/spring-boot-starter

Source: http://mp.weixin.qq.com/s/PUN5nY9-Y_eVej1EvdVTtQ

Video learning reference: http://www.roncoo.com/course/list.html? CourseName = spring + boot

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.