// Transportクラスのオブジェクトを得る
Transport transport = null;
try {
transport = session.getTransport("smtp");
} catch (NoSuchProviderException e) {
// プロバイダが見つからない場合
// デフォルトの設定ではSMTPプロバイダが設定されているため発生しない
}
try {
// SMTPサーバへの接続
transport.connect();
// 送信前に、ヘッダの更新を行う
msg.saveChanges();
// メッセージの送信
transport.sendMessage(msg, msg.getAllRecipients());
// 複数のメッセージを送信する場合sendMessage()メソッドを繰り返し呼び出す。
// transport.sendMessage(msg2, msg2.getAllRecipients());
// ...
} catch (MessagingException e) {
// SMTPサーバへの接続、メッセージの送信失敗時
} finally {
try{
// SMTPサーバからの切断
transport.close();
}catch(MessagingException e){
// サーバ切断失敗時
}
} |