Mailの送信手順を次に示します。
1.JavaMailリソースのlookup処理
JavaMailリソースのlookup処理を行います。
// Mailリソースのlookup処理
InitialContext nctx = new InitialContext();
session = (Session) nctx.lookup("java:comp/env/mail/MailSession");
}
catch(NamingException ex) { }2.メッセージの作成
送信するメッセージを作成します。
メッセージには次の内容を設定します。
送信者(From)
宛先(To)
宛先(Cc)
宛先(Bcc)
題名(Subject)
本文
// メッセージの作成
MimeMessage msg = null;
try {
// メッセージの生成
msg = new MimeMessage(session);
// 送信者(From)の設定
msg.setFrom(new InternetAddress("<from-address>"));
// 宛先(To)の設定
Address[] toAddress = {new InternetAddress("<to-address>")};
msg.setRecipients(Message.RecipientType.TO, toAddress);
// 宛先(Cc)の設定
Address[] ccAddress = {new InternetAddress("<cc-address>")};
msg.setRecipients(Message.RecipientType.CC, ccAddress);
// 宛先(Bcc)の設定
Address[] bccAddress = {new InternetAddress("<bcc-address>")};
msg.setRecipients(Message.RecipientType.BCC, bccAddress);
// 題名(Subject)の設定
String subject = new String("<Subject>");
msg.setSubject(subject);
// 本文の設定
String msgTxt = new String("<Message Text>");
msg.setText(msgTxt);
}
catch(AddressException ex) { }
catch(MessagingException ex) { }3.SMTPサーバとの接続
SMTPサーバに接続します。
// SMTPサーバとの接続
Transport transport = null;
try {
transport = session.getTransport("smtp");
transport.connect();
}
catch(NoSuchProviderException ex) { }
catch(MessagingException ex) { }4.メッセージの送信
作成したメッセージを送信します。
// メッセージの送信
try {
transport.send(msg);
}
catch(MessagingException ex) { }