jakarta プロジェクトの commons-email たいへん便利ですね。
あれだけしちめんどくさいBASE64エンコードしてmime/multipartに
組みなおしてだのの処理を引き受けてくれるので簡単にHTMLメールだの
添付ファイル付きのメールだのをJavaで送信できます。
ただ一回のSMTPコネクションで同時に複数のメールを送信することは
あまり考慮されていません。
アラート機能やメルマガ等々実際プログラムしていると複数の
時には大量のメールを一度に配信しなければならないことも多い
のでこれは不便です。
ということでコレ無理やりやってみました。
Jakarta Commons Email
http://commons.apache.org/email/
(基本的な使い方は扱いません↑DLするとexample付いてくるのでそれでも見てください)
◆基本形はこんな感じ
HtmlEmail email = new HtmlEmail();
email.setFrom("from@hoge");
email.setHostName("localhost");
email.setSentDate(Calendar.getInstance().getTime());
email.setSubject("example title");
email.setCharset("iso-2022-jp");
URL image_url = new URL("file:/home/homepage/public_html/image/test.gif");
String cid = email.embed(image_url, "test.gif");
email.setHtmlMsg("<html><body><img src=\"cid:"+cid+"\" /></body></html>");
email.setTextMsg("test");
//Vector Dummyto = new Vector();
//Dummyto.add(new InternetAddress("to@hoge"));
//email.setTo(Dummyto);
email.addTo("to@hoge");
email.send();
◆メルマガを想定成功例(送信先だけ返るBCCは使わない)
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
props.put("mail.host", "localhost");
props.put("mail.from", "from@hoge");
props.put("mail.smtp.from", "from@hoge");
javax.mail.Session mail_session = javax.mail.Session.getInstance(props);
Transport transport = mail_session.getTransport("smtp");
transport.connect();
HtmlEmail email = new HtmlEmail();
email.setFrom("from@hoge");
email.setHostName("localhost");
email.setSentDate(Calendar.getInstance().getTime());
email.setSubject("example title");
email.setCharset("iso-2022-jp");
URL image_url = new URL("file:/home/homepage/public_html/image/test.gif");
String cid = email.embed(image_url, "test.gif");
email.setHtmlMsg("<html><body><img src=\"cid:"+cid+"\" /></body></html>");
email.setTextMsg("test");
email.addTo("to@hoge");
email.buildMimeMessage(); //ポイントgetMimeMessage();で返されるmessageはこの関数で精製される
MimeMessage message = email.getMimeMessage();
for(int i=0;i<10;i++){
InternetAddress[] to_array = {new InternetAddress( "to"+i+"@hoge")};
message.setRecipients(Message.RecipientType.TO,to_array);
transport.sendMessage(message,to_array);
}
transport.close();
ポイント①
javax.mail のTransportクラスでSMTP接続を制御できる。
MimeMessageを精製できればTransportクラスに渡すことが可能になる。
ポイント②
email.buildMimeMessage(); とMimeMessage message = email.getMimeMessage();で
MimeMessageを作成してあて先の書き換えにはMimeMessageを使用する。
HtmlMailクラス等は基本的に書き換えを考慮していない。
◆失敗例―コード省略概要
HtmlEmail には addTo 以外にも setToがあったりするこれを利用しようとしたが
HtmlEmail は書き換えを想定していないらしく2度目以降のemail.buildMimeMessage();
で不可解なMimeMessageを精製するようになる(画像も本文も2倍になる)
最近のコメント