繁体   English   中英

在我的Spring Boot Web应用程序中,如何在没有模板引擎的情况下发送包含html的电子邮件>

[英]In my Spring Boot web application, how can I send an email containing html without a templating engine>

我目前有一个Spring Boot Web应用程序,我想发送一封包含HTML的电子邮件,因此该电子邮件看起来更令人愉悦。 目前,我正在使用SimpleMailMessage。

我宁愿不仅仅为了发送格式正确的电子邮件而实现模板引擎。

感谢所有帮助,谢谢。

如果您实际上使用的是Spring Boot,那么您就已经有了一个非常不错的发送消息的开始。 您的代码可以宽松地基于以下简单内容:

@Component
public class EmailServiceImpl implements EmailService {

    @Autowired
    public JavaMailSender emailSender;

    @Autowired
    public MimeMessage mimeMessage;

    public void sendMessage() {
       helper.setTo("someone@abc.com");
       helper.setSubject("This is the test message for testing gmail smtp server using spring mail");
       helper.setFrom("abc@gmail.com");
       mailSender.send(mimeMessage);
    }
}

外观中的@Configuration包含您的模板:

@Bean
@Scope("prototype")
public MimeMessage templateSimpleMessage(JavaMailSender mailSender) {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    helper.setText("<h3>Hello World!</h3>");
    return message;
}

只需像在application.yml那样配置您的邮件SMTP目标:

# application.yml

spring:
  mail:
    default-encoding: UTF-8
    host: smtp.gmail.com
    username: [email protected]
    password: secret
    port: 587
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
    protocol: smtp
    test-connection: false

如果要构建更高级的模板,请使用Velocity 参见示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM