JavaMailでOP25B対応
SMTPの25番ポートを使えないプロバイダが最近増えていると思います。
この場合ポートを指定したり、認証後にメールを送信しなければならないわけですが、JavaMailで実装してみました。
以下のような感じです。
Properties properties = new Properties();
// SMTPサーバーのアドレスを指定
properties.put("mail.smtp.auth","true");
// session作成
Session session = Session.getDefaultInstance(properties,null);
MimeMessage message = new MimeMessage(session);
// 送信元アドレス
message.setFrom(new InternetAddress("xxx@xxx.jp"));
// サブジェクト
message.setSubject("subject","iso-2022-jp");
// メール本文
message.setText("text","iso-2022-jp");
// 送信日付
message.setSentDate(new Date());
// サービス接続
Transport tp = session.getTransport("smtp");
tp.connect( "SMTPホスト", SMTPポート, ユーザーID, パスワード );
// 送信先アドレス
InternetAddress[] to = { new InternetAddress("yyy@yyy.jp") };
tp.sendMessage( message, to );
2つだけ特筆事項を
その1
Properties properties = new Properties();は、よくサンプルなどで
Properties properties = System.getProperties();となっていますが、newするほうをお勧めします。
Systemプロパティを書き換えると、複数のアプリが動作するVMではメールの設定が上書きされてしまいます。
その2
// SMTPサーバーのアドレスを指定は
properties.put("mail.smtp.auth","true");
// SMTPサーバーのアドレスを指定ではNGで、文字列を設定する必要がありました。
boolean auth = true;
properties.put("mail.smtp.auth",auth);
環境によってはポート指定や認証が必要ない場合もありますがので、使い分けしていただければと思います。
2008/5/29 追記
サンプルコードを一部修正しました。
こちらをご参照ください。
Posted in Java |

5月 29th, 2008 at 11:52:30
[…] JavaMailでOP25B対応 […]