在此页面上,我们将探索如何使用 Spring Boot 和 FreeMarker 发送电子邮件。 FreeMarkerTemplateUtils
是一个用于使用 FreeMarker 模板发送电子邮件的实用程序类。
String htmlText= FreeMarkerTemplateUtils.processTemplateIntoString(Template template, Object model);
它以字符串的形式返回处理后的 HTML 并抛出:
IOException
– 如果模板在指定路径上不可用。
TemplateException
– 如果模板中指定错误,则解析异常。
请参阅与如何使用 Spring Boot 示例发送电子邮件不同的代码片段。
....
FreeMarkerConfigurer freemarkerConfig;
{
Template t = freemarkerConfig.getConfiguration().getTemplate("/email/welcome.ftlh");
String htmlText= FreeMarkerTemplateUtils.processTemplateIntoString(t, dataMap);
}
....
// We can also get a Template object like this...
...
Configuration config;
{
Template t = config.getTemplate("/email/welcome.ftlh");
String htmlText= FreeMarkerTemplateUtils.processTemplateIntoString(t, dataMap);
}
...
注意: Spring Boot 最近将默认扩展名从 .ftl
更改为 .ftlh
查找此应用程序中使用的所有工具/技术的列表。
将以下依赖项添加到 pom.xml.
pom.xml
<!-- FreeMarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- Java Mailer -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
我们在 STS 4 IDE 中的应用程序的最终项目结构如下所示:
在 application.properties 文件中定义邮件服务器属性。
application.properties
# Mail server properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=XXXXXXXXXXX
spring.mail.password=xxxxxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.properties.mail.smtp.starttls.enable=true
EmailDTO
对象用于作为参数传递给我们的 EmailService
以封装电子邮件的详细信息,如收件人电子邮件、电子邮件主题等。
电子邮件DTO.java
package org.websparrow.dto;
import java.util.Map;
public class EmailDTO {
private String to;
private String subject;
private Map<String, Object> emailData;
// Generate Getters and Setters...
}
一个服务类,它实际将数据拉取到模板并将电子邮件发送到收件人地址。
EmailService.java
package org.websparrow.service;
import java.nio.charset.StandardCharsets;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.websparrow.dto.EmailDTO;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private FreeMarkerConfigurer freemarkerConfig;
public void sendWelcomeEmail(EmailDTO emailDTO) {
System.out.println("##### Started sending welcome email ####");
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
String templateContent = FreeMarkerTemplateUtils
.processTemplateIntoString(freemarkerConfig.getConfiguration()
.getTemplate("/email/welcome.ftlh"),
emailDTO.getEmailData());
helper.setTo(emailDTO.getTo());
helper.setSubject(emailDTO.getSubject());
helper.setText(templateContent, true);
mailSender.send(mimeMessage);
System.out.println("######## Welcome email sent ######");
} catch (Exception e) {
System.out.println("Sending welcome email failed, check log...");
e.printStackTrace();
}
}
}
创建您漂亮的 HTML 电子邮件模板并将其放在 src/main/resources/templates/email
文件夹下。确保模板的文件扩展名必须是 .ftlh
。
欢迎.ftlh
<!DOCTYPE html>
<html>
<head>
<title>Welcome Letter</title>
</head>
<body>
<h3>Dear ${name},</h3>
<p>A warm welcome and lots of good wishes on becoming part of our growing team.</p>
<p>We are pleased to inform you that you will work with the following team members:</p>
<ol>
<#list teamMembers as teamMember>
<li>${teamMember}</li>
</#list>
</ol>
<p>Regards</p>
<p>Websparrow.org Team</p>
<p>Location: ${location}</p>
</body>
</html>
创建一个EmailDTO
对象并设置必要的数据,调用EmailService
发送邮件。
SBFreeMarkerEmailApp.java
package org.websparrow;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.websparrow.dto.EmailDTO;
import org.websparrow.service.EmailService;
@SpringBootApplication
public class SBFreeMarkerEmailApp implements CommandLineRunner {
@Autowired
private EmailService emailService;
@Override
public void run(String... args) throws Exception {
System.out.println("###### Email sending initiated ######");
EmailDTO email = new EmailDTO();
email.setTo("websparrow.org@gmail.com");
email.setSubject("Welcome Letter via Spring Boot + FreeMarker");
// Populate the template data
Map<String, Object> templateData = new HashMap<>();
templateData.put("name", "Atul Rai");
// List of team members...
List<String> teamMembers = Arrays.asList("Tendulkar", "Manish", "Dhirendra");
templateData.put("teamMembers", teamMembers);
templateData.put("location", "India");
email.setEmailData(templateData);
// Calling email service
emailService.sendWelcomeEmail(email);
}
public static void main(String[] args) {
SpringApplication.run(SBFreeMarkerEmailApp.class, args);
}
}
通过执行上述类启动您的应用程序,如果一切配置正确,您将在提供的电子邮件地址上收到一封电子邮件。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/spring/spring-boot-send-email-using-freemarker
内容来源于网络,如有侵权,请联系作者删除!