我试图发送一封带有弹簧启动和模板Thymeleaf的电子邮件。理论上一切正常,电子邮件被发送,但实际上收件人获得了干净的HTML代码。我不知道出了什么问题。模板代码可能是正确的。你能告诉我出了什么问题吗?
@Service
public class MailService {
@Autowired
@Qualifier("JavaEmailConfig")
public JavaMailSender emailSender;
@Autowired
@Qualifier("templateEngine")
public SpringTemplateEngine templateEngine;
public String build(Object object, String temp) {
Context context = new Context();
context.setVariable("object", object);
return templateEngine.process(temp, context);
}
public void sendEmail(String to, String subject, Object object, String temp) {
MimeMessagePreparator messagePreparator = mimeMessage -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
String content = build(list,object,temp);
messageHelper.setText(content);
};
try {
emailSender.send(messagePreparator);
} catch (MailException e) {
}
}
}
MailConfig:
@Configuration
public class MailConfig {
private String host="smtp.gmail.com";
private String port="587"
private String username;
private String password;
@Bean(name = "JavaEmailConfig")
public JavaMailSenderImpl javaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(Integer.parseInt(port));
mailSender.setUsername(username);
mailSender.setPassword(password);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
}
简单编码temp:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<p>Hello! I`m sending email :) </p>
</body>
</html>