0

私は現在、Java (Amazon EC2 インスタンス) でコーディングされたサーバーを持っています。このサーバーには、さまざまな 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);  
            }
        }

これで、コードによって生成された外部変数に基づいて、人の名前を含むメールを正常に送信できました。私の質問は、より複雑な HTML メールでこれを行うにはどうすればよいですか? より複雑なレイアウトの HTML ファイルを生成しましたが、コードでこれらの変数を変更する必要があります。このファイルは HTML であるため、大きなテキスト文字列として読み取って htmlVer 文字列に追加するだけでよいと思います (よくわかりません)。しかし、HTML ファイルを読み取り、いくつかの変数を変更して、これを Amazon SES のコンテンツ部分に追加するだけの簡単な方法があるかどうか疑問に思っていました。

ここで間違ったアプローチをとっていますか?

4

1 に答える 1

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 ファイルを処理した後、htmlJava コードの変数には上記の HTML が含まれますが、<p>要素の内容はコンテキストで渡された値に置き換えられます。

DreamWeaver などのツールを使用して HTML を作成している場合は、問題ありません。テキスト エディターを使用して、th:text後で (またはその他の) 属性を追加できます。これは Thymeleaf の強みの 1 つです。テンプレートと Java コードを別々に作成し、必要なときにそれらを結合できます。

于 2013-04-02T02:52:12.700 に答える