使用Spring Boot时如何使用SpringTemplateEngine

使用Spring Boot时如何使用SpringTemplateEngine,第1张

使用Spring Boot时如何使用SpringTemplateEngine

您正在使用Spring Boot,然后让Spring
Boot完成已经完成的繁重工作。删除你的构造,简单

@Autowire
JavaMailSender
SpringTemplateEngine

将邮件配置添加到中

application.properties

spring.mail.host=your-mail-serverspring.mail.port=spring.mail.usernamespring.mail.password

百里香叶配置添加到application.properties

# THYMELEAF (ThymeleafAutoConfiguration)spring.thymeleaf.check-template-location=truespring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.excluded-view-names= # comma-separated list of view names   that should be excluded from resolutionspring.thymeleaf.view-names= # comma-separated list of view names that can be resolvedspring.thymeleaf.suffix=.htmlspring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8spring.thymeleaf.content-type=text/html # ;charset=<encoding> is addedspring.thymeleaf.cache=true # set to false for hot refresh

如果您这样做了,就改变您的班级

@Servicepublic class MailService {    @Autowired    private JavaMailSender mailSender;    @Autowired    private SpringTemplateEngine templateEngine;    @Value("${spring.mail.username}")    private String username;    public void enviarRelatorio(String nome, String email, String obra,long medicao, Locale locale) throws MessagingException {        String subject = "Novo relatório";        final Context ctx = new Context(locale);        ctx.setVariable("nome", nome);        ctx.setVariable("obra", obra);        ctx.setVariable("data", DataUtils.getInstance().getDataString(medicao));        ctx.setVariable("logo", "logo.jpg");        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true, "UTF-8");        message.setSubject(subject);        message.setTo(email);        try { message.setFrom(new InternetAddress(username, "Sistema"));        } catch (UnsupportedEncodingException e) {        }        final String htmlContent = this.templateEngine.process( "email-relatorio", ctx);        message.setText(htmlContent, true);        try { message.addInline("logo.jpg", new FileSystemResource("imgs/logo-pro.jpg"), "image/jpg");        } catch (IOException e) { e.printStackTrace();        }        this.mailSender.send(mimeMessage);    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5641473.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存