如何使用百里香从html获取数据?

时间:2019-01-31 11:16:39

标签: html spring thymeleaf

我使用thymeleaf通过邮件发送消息,我使用Contex()设置具有用户字段的变量。问题是什么?问题是,当您从邮件中的模板发送数据时,将发送整个html代码,但是您只需要一条消息。我认为看代码会更清楚

 Context context = new Context();
    context.setVariable("name", user.getUsername());
    context.setVariable("activationCode", user.getActivationCode());
    MvcConfig mvcConfig = new MvcConfig();
    TemplateEngine templateEngine = mvcConfig.templateEngine();
    String text = templateEngine.process("email-template",context);
    if (!org.springframework.util.StringUtils.isEmpty(user.getEmail())) {
        //TODO: move to template

        mailSenderService.send(user.getEmail(), "Activation code", text);
    }




@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.addTemplateResolver(new UrlTemplateResolver());
    templateEngine.setTemplateResolver(templateResolver());
    return templateEngine;
}

enter image description here

以这种形式出现在邮件中,但是应该是这样的 您好亲爱的,拉扎 欢迎使用。请访问http://aa.ru/activate-account/blalblalbla

3 个答案:

答案 0 :(得分:0)

请如下更改您的templateEngine()方法:

@Bean
public ITemplateEngine htmlTemplateEngine() {
   SpringTemplateEngine templateEngine = new SpringTemplateEngine();
   ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
   templateResolver.setPrefix("/");
   templateResolver.setSuffix(".html");
   templateResolver.setTemplateMode(TemplateMode.HTML); // Important line is here for HTML!!!
   templateResolver.setCacheable(false);
   templateEngine.setTemplateResolver(templateResolver);
   return templateEngine;
}

请注意TemplateMode.HTML

答案 1 :(得分:0)

根据https://www.thymeleaf.org/doc/articles/springmail.html

private ITemplateResolver htmlTemplateResolver() {
        final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setOrder(Integer.valueOf(2));
        templateResolver.setResolvablePatterns(Collections.singleton("html/*"));
        templateResolver.setPrefix("/mail/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING);
        templateResolver.setCacheable(false);
        return templateResolver;
    }

    @Bean
        public TemplateEngine emailTemplateEngine() {
            final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
     // Resolver for HTML emails (except the editable one)
            templateEngine.addTemplateResolver(htmlTemplateResolver());
...
}

答案 2 :(得分:0)

* {
transition: 1s;
}

我在发送邮件的方法中添加了内容,它解决了问题