spring 如何在Thymeleaf中使用javax邮件

i86rm4rw  于 2023-04-10  发布在  Spring
关注(0)|答案(1)|浏览(175)

我已经搜索了很多,但没有找到任何答案,使用thymeleaf模板与javax.mail每个例子是使用spring-boot-starter-mail
你们谁有解决办法吗
这是我使用的代码:

  1. package com.journaldev.mail;
  2. import java.util.Properties;
  3. import javax.mail.Session;
  4. public class SimpleEmail {
  5. public static void main(String[] args) {
  6. System.out.println("SimpleEmail Start");
  7. String smtpHostServer = "smtp.example.com";
  8. String emailID = "email_me@example.com";
  9. Properties props = System.getProperties();
  10. props.put("mail.smtp.host", smtpHostServer);
  11. Session session = Session.getInstance(props, null);
  12. EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Subject", "SimpleEmail Testing Body");
  13. }
  14. }
smdnsysy

smdnsysy1#

  1. import java.util.Properties;
  2. import javax.mail.Message;
  3. import javax.mail.MessagingException;
  4. import javax.mail.Session;
  5. import javax.mail.Transport;
  6. import javax.mail.internet.InternetAddress;
  7. import javax.mail.internet.MimeMessage;
  8. import org.thymeleaf.TemplateEngine;
  9. import org.thymeleaf.context.Context;
  10. import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
  11. public class ThymeleafEmail {
  12. public static void main(String[] args) throws MessagingException {
  13. // Set mail properties
  14. Properties props = new Properties();
  15. props.put("mail.smtp.host", "smtp.gmail.com");
  16. props.put("mail.smtp.port", "587");
  17. props.put("mail.smtp.auth", "true");
  18. props.put("mail.smtp.starttls.enable", "true");
  19. // Get the Session object
  20. Session session = Session.getDefaultInstance(props);
  21. // Prepare the Thymeleaf template
  22. ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
  23. resolver.setTemplateMode("HTML");
  24. resolver.setSuffix(".html");
  25. TemplateEngine templateEngine = new TemplateEngine();
  26. templateEngine.setTemplateResolver(resolver);
  27. Context context = new Context();
  28. context.setVariable("name", "John Doe");
  29. String processedTemplate = templateEngine.process("email_template", context);
  30. // Create a message
  31. Message message = new MimeMessage(session);
  32. message.setFrom(new InternetAddress("from@example.com"));
  33. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@example.com"));
  34. message.setSubject("Test email with Thymeleaf template");
  35. message.setContent(processedTemplate, "text/html");
  36. // Send the message
  37. Transport.send(message);
  38. System.out.println("Email sent successfully!");
  39. }
  40. }
展开查看全部

相关问题