如何使用java servlet中的变量发送HTML电子邮件?

时间:2013-04-02 01:47:13

标签: java html servlets

我目前有一个用Java编码的服务器(一个亚马逊EC2实例),它有许多servlet来做各种Web服务。到目前为止,我一直在使用以下代码发送邀请电子邮件:

public void sendInvitationEmail(String nameFrom, String emailTo, String withID)
        {

            SendEmailRequest request = new SendEmailRequest().withSource("invitation@myserver.com");

            List<String> toAddresses = new ArrayList<String>();
            toAddresses.add(emailTo);
            Destination dest = new Destination().withToAddresses(toAddresses);
            request.setDestination(dest);

            Content subjContent = new Content().withData("My Service Invitation Email");
            Message msg = new Message().withSubject(subjContent);

            String textVer = nameFrom +" has invited you to try My Service.";
            String htmlVer = "<p>"+nameFrom+" has invited you to try My Service.</p>";
            // Include a body in both text and HTML formats
            Content textContent = new Content().withData(textVer);
            Content htmlContent = new Content().withData(htmlVer);
            Body body = new Body().withHtml(htmlContent).withText(textContent);
            msg.setBody(body);

            request.setMessage(msg);

            try {           
                ses.sendEmail(request);
            }catch (AmazonServiceException ase) {
                handleExceptions(ase);
            } catch (AmazonClientException ace) {
                handleExceptions(ace);  
            }
        }

Whit我已成功发送电子邮件,其中包含基于我的代码生成的外部变量的人名。我的问题是,如何使用更复杂的HTML电子邮件进行此操作?我已经生成了一个具有更复杂布局的HTML文件,但我仍然需要通过我的代码修改这些变量。该文件是一个HTML所以我认为(不确定)我可以将其作为一个大的文本字符串读取,只需将其添加到htmlVer字符串。但我想知道是否有更简单的方法来读取HTML文件并只更改一些变量,然后只需将其添加到Amazon SES的内容部分。

我在这里采取了错误的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用像Thymeleaf这样的模板引擎来处理html和注入属性。

这很简单:

ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setTemplateMode("HTML5");
resolver.setSuffix(".html");
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(resolver);
final Context context = new Context(Locale.CANADA);
String name = "John Doe";
context.setVariable("name", name);

final String html = templateEngine.process("myhtml", context);

使用myhtml.html文件:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>My first template with Thymeleaf</title>
</head>
<body>
    <p th:text="${name}">A Random Name</p> 
</body>
</html>

引擎处理HTML文件后,java代码中的变量html将包含上面的HTML,但会将<p>元素的内容替换为您在上下文中传递的值。

如果您使用像DreamWeaver这样的工具来制作HTML,那不是问题。您可以使用文本编辑器,稍后添加th:text(或其他)属性。这是Thymeleaf的优势之一,您可以单独创建模板和Java代码,并在需要时加入它们。