使用Spring启动使用Template发送电子邮件

时间:2015-09-26 07:07:06

标签: java spring email

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

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.

我还在application.properties

中使用了thymeleaf类路径
spring.thymeleaf.prefix=classpath:/templates

但我一直得到同样的例外。任何人都可以知道解决方案pl帮助我。 以下是我正在使用的源代码。 (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);

    }

}

2 个答案:

答案 0 :(得分:0)

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

this project有完整的操作说明

它使用rest控制器获取电子邮件参数,例如收件人地址,主题和内容,并发送预先格式化的电子邮件。

答案 1 :(得分:0)

尝试添加此依赖项

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