繁体   English   中英

使用 Spring Boot 使用模板发送电子邮件

[英]Sending email with Template using Spring boot

我创建了简单的 spring boot 应用程序并尝试使用电子邮件模板发送电子邮件,但它抛出:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "email-simple.html", template might not exist or might not be accessible by any of the configured Template Resolvers.

我也用在类路径thymeleaf application.properties

spring.thymeleaf.prefix=classpath:/templates

但我不断收到同样的例外。 任何人都可以知道解决方案请帮助我。 下面是我正在使用的源代码。 (1) 我在 pom.xml 中使用了 Thymeleaf <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

(2) 我将 email-simple.html 文件保存在 resources/templates/email-simple.html 中。

(3) 这是我的服务类:

@Component
public class SmptMailSender {

@Autowired
private JavaMailSender javaMailSender;  

 @Autowired 
 private TemplateEngine templateEngine;
 public void sendSimpleMail(final String recipientName, final String    recipientEmail, final Locale locale) 
            throws MessagingException {

        // Prepare the evaluation context
        final Context ctx = new Context(locale);
        ctx.setVariable("name", recipientName);
        ctx.setVariable("subscriptionDate", new Date());
        ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));

        // Prepare message using a Spring helper
        final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject("Example HTML email (simple)");
        message.setFrom("thymeleaf@example.com");
        message.setTo(recipientEmail);

        // Create the HTML body using Thymeleaf
        final String htmlContent = this.templateEngine.process("email-simple.html", ctx);
        message.setText(htmlContent, true /* isHtml */);

        // Send email
        this.javaMailSender.send(mimeMessage);

    }

}

您可以使用 Apache Freemarker 模板来格式化您的电子邮件。

这个项目有关于如何做的完整说明

这使用一个休息控制器来获取电子邮件参数,如接收者地址、主题和内容,并发送预先格式化的电子邮件。

尝试添加此依赖项

   <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
    </dependency>

暂无
暂无

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

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