在Spring Boot应用中使用Freemarker模板发送电子邮件可以通过以下步骤实现:
pom.xml
文件中添加spring-boot-starter-mail
和spring-boot-starter-freemarker
依赖。<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
application.properties
或application.yml
文件中配置邮件发送的相关参数。spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your-email@example.com
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
src/main/resources/templates
目录下创建邮件模板,例如email-template.ftl
。<!DOCTYPE html>
<html>
<head>
<title>Spring Boot Email Example</title>
</head>
<body>
<h1>Hello ${name}!</h1>
<p>This is a sample email template.</p>
</body>
</html>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private Configuration freemarkerConfig;
@Value("${spring.mail.username}")
private String from;
public void sendEmail(String to, String subject, String templateName, Object model) throws Exception {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
Template template = freemarkerConfig.getTemplate(templateName);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
helper.setText(content, true);
mailSender.send(message);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EmailController {
@Autowired
private EmailService emailService;
@RequestMapping("/sendEmail")
public String sendEmail(Model model) {
String to = "recipient@example.com";
String subject = "Test Email";
String templateName = "email-template.ftl";
model.addAttribute("name", "Recipient Name");
try {
emailService.sendEmail(to, subject, templateName, model);
return "Email sent successfully!";
} catch (Exception e) {
return "Email sending failed!";
}
}
}
以上就是在Spring Boot应用中使用Freemarker模板发送电子邮件的步骤。你可以根据实际需求修改模板和发送逻辑。对于电子邮件的发送和模板的使用,Spring Boot提供了方便的封装和集成,使得开发变得更加简单和高效。
推荐的腾讯云相关产品:腾讯云的邮件推送服务(https://cloud.tencent.com/product/tws)可以用于在云平台上发送电子邮件,具有高可用性、低延迟和高成功率的特点。
领取专属 10元无门槛券
手把手带您无忧上云