Spring-boot "12": Send mail using javamailsender in Spring boot

Source: Internet
Author: User
Tags starttls

It is believed that many developers who have used spring know that spring provides a very useful JavaMailSender interface for sending mail. An automated configuration is also provided for this in the Spring Boot starter module. Here's an example of how to use Send mail in spring boot JavaMailSender .

Quick Start

The dependencies are introduced in the Spring Boot project pom.xml spring-boot-starter-mail :

1234 <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-mail</artifactid> </dependency>

As with other automation configuration modules, once dependency ingestion is complete, you only need to application.properties configure the appropriate attribute content in.

Below we take the QQ mailbox as an example, application.properties add the following configuration in (note to replace your own user name and password):

123456 Spring.mail.host=smtp.qq.comspring.mail.username= User name spring.mail.password= Password spring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=True spring.mail.properties.mail.smtp.starttls.required=True

A simple message is sent by unit testing:

12345678910111213141516171819 @RunWith (Springjunit4classrunner.class)@SpringApplicationConfiguration (classes = application.class)public class applicationtests { @Autowiredprivate Javamailsender MailSender;@Testpublic void sendsimplemail() throws Exception { Simplemailmessage message =new Simplemailmessage ();Message.setfrom ("[email protected]");Message.setto ("[email protected]");Message.setsubject ("Subject: Simple Mail");Message.settext ("test message content");Mailsender.send (message);} }

Here, a simple email is done, run the unit test and see how it works?

Since the Spring Boot starter module provides an automated configuration, after the introduction of spring-boot-starter-mail dependencies, the instances are created based on the contents of the configuration file JavaMailSender , so we can directly @Autowired introduce the mail sending object directly where we need it.

Advanced use

In the example above, we SimpleMailMessage implemented a simple e-mail delivery, but in actual use, we may also bring attachments, or use the Mail module. This time we need to use MimeMessage to set up a more complex message content, the following we will be implemented in turn.

Send Attachments

Add the following test case to the above unit test (send a message with an attachment via Mimemessagehelper):

123456789101112131415161718 @Testpublic void sendattachmentsmail() throws Exception { MimeMessage mimemessage = Mailsender.createmimemessage (); Mimemessagehelper helper =New Mimemessagehelper (MimeMessage, true); Helper.setfrom ("[email protected]");Helper.setto ("[email protected]");Helper.setsubject ("Subject: With attachments");Helper.settext ("Mail with Attachments");Filesystemresource file =New Filesystemresource (new File ("weixin.jpg")); Helper.addattachment ("Attachment -1.jpg", file);Helper.addattachment ("Attachment -2.jpg", file);Mailsender.send (MimeMessage); }
Embedding Static Resources

In addition to sending attachments, we may want to embed a static resource such as a picture in the message content to get a better reading experience for the message, instead of viewing the specific picture from the attachment, and the following test case demonstrates how to MimeMessageHelper embed a static resource in the message body by implementing it.

1234567891011121314151617 @Testpublic void sendinlinemail() throws Exception { MimeMessage mimemessage = Mailsender.createmimemessage (); Mimemessagehelper helper =New Mimemessagehelper (MimeMessage, true); Helper.setfrom ("[email protected]");Helper.setto ("[email protected]");Helper.setsubject ("topic: Embedding Static Resources");Helper.settext ("true); Filesystemresource file =New Filesystemresource (new File ("weixin.jpg")); Helper.addinline ("Weixin", file);Mailsender.send (MimeMessage); }

It is important to note that the addInline resource name in the function weixin needs to cid:weixin correspond to the body.

Template Mail

Usually we use the mail to send the service, there are some fixed scenes, such as Reset password, registration confirmation, etc., to each user sent content may only a small part of the change. So, most of the time we use the template engine to set up a template for each type of message, so we just need to replace the parameters of the change section when we send it.

It is also very easy to use the template engine to implement templated mail delivery in spring boot, let's take velocity as an example.

The introduction of the velocity module depends on:

1234 <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-velocity</artifactid> </dependency>

resources/templates/under, create a template page template.vm :

12345 <html> <body> <h3> Hello, ${username}, this is a template mail! </h3></body></html>

When we developed the Web app in spring boot, we mentioned that under the automation configuration of Spring boot, the template is in the directory by default resources/templates/

Finally, we add test cases for sending template messages in unit tests, as follows:

123456789101112131415161718 @Testpublic void sendtemplatemail() throws Exception { MimeMessage mimemessage = Mailsender.createmimemessage (); Mimemessagehelper helper =New Mimemessagehelper (MimeMessage, true); Helper.setfrom ("[email protected]");Helper.setto ("[email protected]");Helper.setsubject ("Subject: Template Mail");map<string, object> model =new Hashedmap ();Model.put (" username", "Didi"); String Text = velocityengineutils.mergetemplateintostring (Velocityengine,"TEMPLATE.VM", "UTF-8", model); Helper.settext (Text,true);Mailsender.send (mimemessage);}

If you try to run it, you will receive 你好, didi, 这是一封模板邮件! a message with the content. Here, we replace the variables in the template with the parameters of the incoming username in the message content ${username} .

Complete Example: chapter4-5-1

"Reprint Please specify source": http://blog.didispace.com/springbootmailsender/

Spring-boot "12": Send mail using javamailsender in 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.