How can i use freemarker to send email with spring-boot? i look in spring-boot examples and dont find anything
I want to generate the body of email with my template
tks
答案 0 :(得分:12)
有一个"配置"您可以作为bean获取的对象:
以下是代码:
package your.package;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import freemarker.template.Configuration;
import freemarker.template.Template;
@Controller
public class MailTemplate {
@Autowired
Configuration configuration;
@RequestMapping("/test")
public @ResponseBody String test2() throws Exception {
// prepare data
Map<String, String> data = new HashMap<>();
data.put("name", "Max Mustermann");
// get template
Template t = configuration.getTemplate("test.html");
String readyParsedTemplate = FreeMarkerTemplateUtils
.processTemplateIntoString(t, data);
// do what ever you want to do with html...
// just for testing:
return readyParsedTemplate;
}
}
答案 1 :(得分:2)
首先,您应该使用Freemarker模板定义电子邮件内容,例如
<html>
<head></head>
<body>
<p>Dear ${firstName} ${lastName},</p>
<p>Sending Email using Spring Boot with <b>FreeMarker template !!!</b></p>
<p>Thanks</p>
<p>${signature}</p>
<p>${location}</p>
</body>
</html>
接下来,创建处理电子邮件模板的电子邮件服务并返回我的消息对象,例如
import java.util.Properties;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import com.javabycode.model.Mail;
import freemarker.template.Configuration;
import freemarker.template.Template;
@Service
public class MailService {
@Autowired
private JavaMailSender sender;
@Autowired
private Configuration freemarkerConfig;
public void sendEmail(Mail mail) throws Exception {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
// Using a subfolder such as /templates here
freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates");
Template t = freemarkerConfig.getTemplate("email-template.ftl");
String text = FreeMarkerTemplateUtils.processTemplateIntoString(t, mail.getModel());
helper.setTo(mail.getMailTo());
helper.setText(text, true);
helper.setSubject(mail.getMailSubject());
sender.send(message);
}
}
但是,这里不适合分享完整的工作示例。您可以参考完成的教程Spring Boot Freemarker Email Template
希望这有帮助!