LoginSignup
10
8

More than 5 years have passed since last update.

commons-emailとhandlerbars.javaでメール送信

Last updated at Posted at 2015-03-19

メール本文のテンプレートをHandlebars.javaで用意して、それをcommons-emailを使って送信したときのメモ。

メールの送信

SimpleEmailのインスタンスをつくって、そいつにSMTPの接続情報、from,toアドレス(cc,bccも可)と件名、本文をセットしていくだけ。


 try {
            SimpleEmail email = new SimpleEmail();
            //接続情報を設定
            email.setHostName("SMTPホスト");
            email.setSmtpPort(25);
            email.setSSLOnConnect(falase);
            email.setAuthentication("SMTPユーザー名", "パスワード");

            //送信内容の設定
            email.setFrom("fromアドレス");
            email.setSubject("件名");

            //テンプレートから本文を生成
            String message = createMessage(messageDto);

            email.setMsg(message);
            email.setCharset("ISO-2022-JP");

            email.addTo("Toアドレス");
            email.send();

        } catch (Exception e) {
            log.error("mail sending failed.", e);
        }

テンプレートから本文生成

テンプレートを読み込んで、対応するオブジェクトでパラメタを解決した結果の文字列を返させる。

private String createMessage(MessageDto messageDto) throws IOException {
        Handlebars handlebars = new Handlebars();
        Template template = handlebars.compile("template"); //デフォルトの拡張子がhbs
        Context context = Context.newBuilder(messageDto).resolver(FieldValueResolver.INSTANCE).build();
        return template.apply(context);
    }

handlebars.javaのテンプレートは下のようなもの。基本は Mustache (http://mustache.github.io/) から派生したものなので、それのルール通り。
{{xxx}}に変数が入る。

template.hbs
{{user}} 様

{{greeting}}

先着{{max}}名までに、{{item}}をプレゼント!

XXXより

今回はテンプレートとオブジェクト(Bean)を対応させたかったので、インスタンスのフィールド名でパラメタを解決させる。そのためには下記のcontextをtemplateにapplyすればよい。

Context context = Context.newBuilder(messageDto).resolver(FieldValueResolver.INSTANCE).build();

これならテンプレートに渡すための型をつくれば、変数の増減の影響範囲をそこでおさまるので、楽そう。
handlebarsも扱いやすそうだし、もっと高度なこともできるので、面倒な要件にも対応できそう。

commons-email

Handlebars.java

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8