I believe that many developers who have used Spring know that Spring provides a very useful JavaMailSender interface for mail sending. The Starter module of Spring Boot also provides automatic configuration for this purpose. The following example shows how to use JavaMailSender to send emails in Spring Boot.
Quick start
Introduce the Spring-Boot-starter-mail dependency to pom. xml in the spring boot project:
<Dependency>
<GroupId> org. springframework. boot </groupId>
<ArtifactId> spring-boot-starter-mail </artifactId>
</Dependency>
Like other automated configuration modules, after dependency introduction is completed, you only need to configure the corresponding attribute content in application. properties.
Take QQ mail as an example. Add the following configuration in application. properties (replace your username and password with caution ):
Spring. mail. host = smtp.qq.com
Spring. mail. username = user name
Spring. mail. password = password
Spring. mail. properties. mail. smtp. auth = true
Spring. mail. properties. mail. smtp. starttls. enable = true
Spring. mail. properties. mail. smtp. starttls. required = true
Send a simple email through unit test:
@ RunWith (SpringJUnit4ClassRunner. class)
@ SpringApplicationConfiguration (classes = Application. class)
Public class ApplicationTests {
@ Autowired
Private JavaMailSender mailSender;
@ Test
Public void sendSimpleMail () throws Exception {
SimpleMailMessage message = new SimpleMailMessage ();
Message. setFrom ("dyc87112@qq.com ");
Message. setTo ("dyc87112@qq.com ");
Message. setSubject ("Subject: Simple Mail ");
Message. setText ("test mail content ");
MailSender. send (message );
}
}
Here, a simple email is sent. Run the unit test to see how it works?
Because the starter module of Spring Boot provides automatic configuration, after the spring-boot-starter-mail dependency is introduced, the JavaMailSender instance will be created based on the content in the configuration file, therefore, you can directly @ Autowired to introduce the email sending object as needed.
Advanced usage
In the preceding example, we use SimpleMailMessage to send a simple email. However, in actual use, we may also include attachments or use the email module. At this time, we need to use MimeMessage to set complicated mail content. Next we will implement it in sequence.
Send attachment
Add the following test cases to the unit test above (send an email with an attachment via MimeMessageHelper ):
@ Test
Public void sendAttachmentsMail () throws Exception {
MimeMessage mimeMessage = mailSender. createMimeMessage ();
MimeMessageHelper helper = new MimeMessageHelper (mimeMessage, true );
Helper. setFrom ("dyc87112@qq.com ");
Helper. setTo ("dyc87112@qq.com ");
Helper. setSubject ("Subject: Attachment ");
Helper. setText ("emails 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 );
}
Embed static resources
In addition to sending attachments, we may want to embed images and other static resources in the content of the email to provide a better reading experience for the email, rather than viewing specific images from the attachment, the following test case demonstrates how to embed static resources in the mail body through MimeMessageHelper.
@ Test
Public void sendInlineMail () throws Exception {
MimeMessage mimeMessage = mailSender. createMimeMessage ();
MimeMessageHelper helper = new MimeMessageHelper (mimeMessage, true );
Helper. setFrom ("dyc87112@qq.com ");
Helper. setTo ("dyc87112@qq.com ");
Helper. setSubject ("topic: embedding static resources ");
Helper. setText ("
FileSystemResource file = new FileSystemResource (new File ("weixin.jpg "));
Helper. addInline ("weixin", file );
MailSender. send (mimeMessage );
}
Note that the resource name weixin in the addInline function must correspond to cid: weixin in the body.
Template email
Generally, when we use the mail sending service, there will be some fixed scenarios, such as resetting the password, registration confirmation, etc. Only a small part of the content sent to each user may change. Therefore, we often use the template engine to set templates for various types of emails. In this way, we only need to replace the parameters of the changed part at the time of sending.
It is also very easy to use the template engine in Spring Boot to implement templated mail sending. The following uses velocity as an example to implement it.
Introduce the dependency of the velocity module:
<Dependency>
<GroupId> org. springframework. boot </groupId>
<ArtifactId> spring-boot-starter-velocity </artifactId>
</Dependency>
Under resources/templates/, create a template page template. vm:
<Html>
<Body>
<H3> Hello, $ {username}. This is a template email! </H3>
</Body>
</Html>
When we used Spring Boot to develop Web applications, we mentioned that in Spring Boot's automated configuration, the template is located under the resources/templates/directory by default.
Finally, we add a test case for sending template emails to the unit test. The details are as follows:
@ Test
Public void sendTemplateMail () throws Exception {
MimeMessage mimeMessage = mailSender. createMimeMessage ();
MimeMessageHelper helper = new MimeMessageHelper (mimeMessage, true );
Helper. setFrom ("dyc87112@qq.com ");
Helper. setTo ("dyc87112@qq.com ");
Helper. setSubject ("Subject: template email ");
Map <String, Object> model = new HashedMap ();
Model. put ("username", "didi ");
String text = VelocityEngineUtils. Mergetemplate1_string (
VelocityEngine, "template. vm", "UTF-8", model );
Helper. setText (text, true );
MailSender. send (mimeMessage );
}
If you try to run it, you will receive the message didi. This is a template email! . Here, the $ {username} variable in the template is replaced in the email content by passing in the username parameter.
Supplementary example: JavaMailSender
I. Pure java
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl ();
SenderImpl. setHost ("smtp.126.com ");
Properties prop = new Properties ();
Prop. setProperty ("mail. smtp. auth", "true ");
SenderImpl. setJavaMailProperties (prop );
SenderImpl. setUsername ("z278440337@126.com ");
SenderImpl. setPassword ("123456 ");
SimpleMailMessage mailMessage = new SimpleMailMessage ();
String [] address = {"z278440337@126.com", "ygchen@unicomsys.net "};
MailMessage. setTo (address );
MailMessage. setFrom ("z278440337@126.com ,");
MailMessage. setSubject ("Email Test ");
MailMessage. setText ("new question complete .");
SenderImpl. send (mailMessage );
II. Configuration file
1. xml file
<Bean name = "mailSender" class = "org. springframework. mail. javamail. JavaMailSenderImpl">
<Property name = "host">
<Value> smtp.126.com </value>
</Property>
<Property name = "javaMailProperties">
<Props>
<Prop key = "mail. smtp. auth"> true </prop>
</Props>
</Property>
<Property name = "username">
<Value> z278440337@126.com </value>
</Property>
<Property name = "password">
<Value> 123456 </value>
</Property>
</Bean>
<Bean name = "mailMessage" class = "org. springframework. mail. SimpleMailMessage">
<Property name = "to">
<Value> ygchen@unicomsys.net </value>
</Property>
<Property name = "from">
<Value> z278440337@126.com </value>
</Property>
<Property name = "subject">
<Value> Default Java Email Title </value>
</Property>
</Bean>
2. java files
SimpleMailMessage message = new SimpleMailMessage (mailMessage );
Message. setSubject ("new Question ");
UserInfo wantAnswerUserInfo = userInfoDAO. findUserByUserID (wantAnswerUser );
String toAddress = wantAnswerUserInfo. getEmail ();
System. out. println (toAddress );
Message. setTo (toAddress );
Message. setText ("complete create new question .");
Try {
MailSender. send (message );
} Catch (MailException e ){
E. printStackTrace ();
}