


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\" ></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>你好, ${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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

PHP development practice: Use PHPMailer to send emails to users in the MySQL database Introduction: In the construction of the modern Internet, email is an important communication tool. Whether it is user registration, password reset, or order confirmation in e-commerce, sending emails is an essential function. This article will introduce how to use PHPMailer to send emails and save the email information to the user information table in the MySQL database. 1. Install the PHPMailer library PHPMailer is

SpringBoot and SpringCloud are both extensions of Spring Framework that help developers build and deploy microservice applications faster, but they each have different purposes and functions. SpringBoot is a framework for quickly building Java applications, allowing developers to create and deploy Spring-based applications faster. It provides a simple, easy-to-understand way to build stand-alone, executable Spring applications

How to use Flask-Mail to send emails With the development of the Internet, email has become an important tool for people to communicate. When developing web applications, sometimes we need to send emails in specific scenarios, such as sending a welcome email after a user successfully registers, or sending a password reset email when a user forgets their password, etc. Flask is a simple and flexible Python Web framework, and Flask-Mail is an extension library for sending emails under the Flask framework. This article will introduce how to

With the update and iteration of technology, Java5.0 began to support annotations. As the leading framework in Java, spring has slowly begun to abandon xml configuration since it was updated to version 2.5, and more annotations are used to control the spring framework.

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.
