


Example of how to use JavaMailSender to send emails in Spring Boot (source code attached)
This article mainly introduces examples of how to use JavaMailSender to send emails in Spring Boot. I believe that many developers who have used Spring know that Spring provides a very easy-to-use JavaMailSender interface to send emails. Automatic configuration is also provided in Spring Boot's Starter module. Friends in need can refer to it.
Quick Start
Introduce the spring-boot-starter-mail dependency into 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 completing the dependency introduction, you only need to configure it in application.properties
The corresponding attribute content.
Let’s take QQ mailbox as an example and add the following configuration to application.properties
(note to replace your username and password):
spring.mail.host=smtp.qq.com spring.mail.username=用户名 spring.mail.password=密码 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
Use unit testing to send a simple email:
@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("主题:简单邮件"); message.setText("测试邮件内容"); mailSender.send(message); } }
Here, a simple The email sending is complete. Run the unit test and see what the effect is?
"Since Spring Boot's starter module provides automated configuration, after introducing the spring-boot-starter-mail dependency, a JavaMailSender instance will be created based on the content in the configuration file, so we can directly configure it when needed Use @Autowired directly to introduce the mail sending object. ”
Advanced use
In the above example, we implement it by using SimpleMailMessage. It is used for simple email sending, but in actual use, we may also bring attachments, or use the email module, etc. At this time we need to use MimeMessage to set more complex email content. Let's implement it in sequence.
Send attachment
Add the following test case to the above unit test (send an email with an attachment through 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("主题:有附件"); helper.setText("有附件的邮件"); FileSystemResource file = new FileSystemResource(new File("weixin.jpg")); helper.addAttachment("附件-1.jpg", file); helper.addAttachment("附件-2.jpg", file); mailSender.send(mimeMessage); }
Embed static resources
In addition to sending attachments, we may want to embed static resources such as pictures in the email content to make the email obtain For a better reading experience, instead of viewing specific images from attachments, the following test case demonstrates how to embed static resources in the email 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("主题:嵌入静态资源"); helper.setText("<html><body><img src=\"cid:weixin\" alt="Example of how to use JavaMailSender to send emails in Spring Boot (source code attached)" ></body></html>", true); FileSystemResource file = new FileSystemResource(new File("weixin.jpg")); helper.addInline("weixin", file); mailSender.send(mimeMessage); }
What needs to be noted here is that the resource name weixin in the addInline function needs to correspond to the cid:weixin in the text
Template email
Usually when we use email sending services, there will be some fixed scenarios, such as password reset, registration confirmation, etc., and only a small part of the content sent to each user may change. Therefore, many times we will use a template engine to set templates for various types of emails, so that we only need to replace the changed parameters when sending.
It is also very easy to use the template engine in Spring Boot to implement templated email sending. Let’s take Velocity as an example to implement it.
Introduce the dependencies 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 id="你好-nbsp-username-nbsp-这是一封模板邮件">你好, ${username}, 这是一封模板邮件!</h3> </body> </html>
When we developed web applications in Spring Boot before, we mentioned that under the automated configuration of Spring Boot, templates are located in the resources/templates/ directory by default
Finally, we add a test case for sending template emails to the unit test, 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("主题:模板邮件"); 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); }
Try running it, and you will receive the content for you Okay, didi, this is a template email! Email. Here, we replace the ${username}
variable in the template in the email content by passing in the username parameter.
The above is the detailed content of Example of how to use JavaMailSender to send emails in Spring Boot (source code attached). For more information, please follow other related articles on the PHP Chinese website!

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

RuoYi framework circular dependency problem troubleshooting and solving the problem of circular dependency when using RuoYi framework for development, we often encounter circular dependency problems, which often leads to the program...

About SpringCloudAlibaba microservices modular development using SpringCloud...

Questions about a curve integral This article will answer a curve integral question. The questioner had a question about the standard answer to a sample question...

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

JDBC...

Why can't the main class be found after copying and pasting the package in IDEA? Using IntelliJIDEA...

State synchronization between Java multi-interface calls: How to ensure that interface A is called after it is executed? In Java development, you often encounter multiple calls...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.