To use Thymeleaf with Spring Boot to send emails, you will need to add the Thymeleaf dependency to your project and configure the Spring Boot mail support.
To add the Thymeleaf dependency to your project, you can include the following dependency in your build file (such as pom.xml
if you are using Maven):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
This dependency includes the Thymeleaf library and the Spring Boot starter for Thymeleaf, which configures the Thymeleaf engine and integrates it with Spring Boot.
To enable Spring Boot mail support, you will need to include the spring-boot-starter-mail
dependency and configure the mail properties in your application configuration.
Here's an example of how you can configure the mail properties in a application.properties
file:
spring.mail.host=smtp.gmail.com spring.mail.username=<your-username> spring.mail.password=<your-password>
Once you have added the dependencies and configured the mail properties, you can use the JavaMailSender
interface and the Thymeleaf template engine to send emails with Spring Boot.
Here's an example of how you can send an email using Thymeleaf and Spring Boot:
@Autowired private JavaMailSender mailSender; @Autowired private TemplateEngine templateEngine; ... // create a mail message MimeMessage message = mailSender.createMimeMessage(); // set the recipient, subject, and message message.setRecipients(MimeMessage.RecipientType.TO, "recipient@example.com"); message.setSubject("Subject"); // create the Thymeleaf template context Context context = new Context(); context.setVariable("name", "John"); // process the template and get the resulting HTML String html = templateEngine.process("template.html", context); // set the HTML content as the message body message.setContent(html, "text/html"); // send the email mailSender.send(message);
In this example, the JavaMailSender
interface is used to create a MIME message and set the recipient,