【发布时间】:2020-01-21 22:18:39
【问题描述】:
我想创建一个服务来使用带有MimeMessage 的 Spring 电子邮件发送 HTML 邮件。这是我的服务:
public void sendHtmlEmail(String receiver,String Subject, String htmlBody) throws MessagingException {
MimeMessage msg = javaMailSender.createMimeMessage();
// true = multipart message
MimeMessageHelper helper = new MimeMessageHelper(msg, false);
helper.setTo(receiver);
helper.setSubject(Subject);
// true = text/html
helper.setText(htmlBody, true);
javaMailSender.send(msg);
}
问题是我没有收到html中的电子邮件,而是html中的标签,知道我在方法setText()中输入了true!我发送的电子邮件以纯 html 文本显示,如下所示
<html><h1>some text !</h1></html>
一些可以帮助你的链接:
https://mkyong.com/spring-boot/spring-boot-how-to-send-email-via-smtp/
https://www.baeldung.com/spring-email
这是 application.properties :
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=username
spring.mail.password=password
# Other properties
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
# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true
和控制器
@PostMapping("/htmlMail")
public String sendHtmlMail(@RequestBody MailDTO mail) {
mailService.sendHtmlEmail(mail.getReceiver(),mail.getSubject(),mail.getHtmlbody());
return "html E-Mail Sent ! ";
}
【问题讨论】:
-
将
properties.put("mail.debug", "true");设置到您的JavaMailSenderbean 中,以准确查看传输的标头和有效负载。 -
代码似乎没问题。也许您可以尝试另一个版本,以确保这不是您当前版本的错误。
-
我也觉得你的代码没问题。尝试在 MimeMessageHelper 对象中添加编码类型“UTF-8”。您能否提供有关您的代码或错误快照的更多详细信息?或尝试我在答案中放置的解决方案,希望对您有所帮助。
-
好吧,当我将选项 debug 设置为 true 时,我得到 Content-Type: text/plain;字符集=UTF-8 !这不是我想要的(我在 setText() 方法中输入了 true,所以我应该有 html 类型):/
标签: java spring spring-boot jakarta-mail html-email