【Java】Apache Velocity & Commons Email
Apache VelocityというテンプレートエンジンとApache Commons Emailを使って、テンプレートによるメール送信を書いてみた。
mailform.htmlの中
名前:<input type="text" id="strName" /><br /> メールアドレス:<input type="text" id="strAddress1" />@<input type="text" id="strAddress2" /><br /> 商品名:<input type="text" id="strProduct"/><br /> 商品数:<input type="text" id="intProduct"/><br /> <input type="button" id="doPurchase" value="購入" /><br />
上記htmlのボタンで指定しているMailFormPage.java内のdoPurchaseメソッド
public Class<?> doPurchase() { String msg = new String(); // Property Properties prop = new Properties(); prop.setProperty("resource.loader", "class"); prop.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); prop.setProperty("class.resource.loader.cache", "true"); prop.setProperty("input.encoding", "UTF-8"); // VelocityEngine VelocityEngine engine = new VelocityEngine(); engine.init(prop); VelocityContext cntxt = new VelocityContext(); cntxt.put("strName", getStrName()); cntxt.put("strProduct", getStrProduct()); cntxt.put("intProduct", getIntProduct()); // Template Template template = engine.getTemplate("mail/mail_template.vm"); StringWriter writer = new StringWriter(); template.merge(cntxt, writer); msg = writer.toString(); try { SimpleEmail email = new SimpleEmail(); StringBuilder mail_address = new StringBuilder(); mail_address.append(getStrAddress1()); mail_address.append("@"); mail_address.append(getStrAddress2()); String _address = mail_address.toString(); email.setHostName("ホストサーバ"); email.addTo(_address, "To : " + getStrName()); // 宛先アドレス email.setFrom(_address, "From : " + getStrName()); // 送信者アドレス(自分自身にしている) email.setSubject("商品購入確認メール"); email.setMsg(msg); email.setCharset("ISO-2022-JP"); email.send(); } catch (Exception e) { e.printStackTrace(); } return FinishPage.class; }
Velocityで使うテンプレートファイルmail_template.vm
${strName}様 ※このメールは確認メールです この度は弊社商品${strProduct}を ${intProduct}個ご購入いただき、誠にありがとうございます。
${}のトコロに、動的に値を送り込んでいるわけです。
データベースも使っていないしセキュリティも考慮していないのだが、とりあえず出来た。次は、データベースへの登録なども絡めて。