JavaMail APIでメールアプリケーションを作成するサンプル
環境
mail-1.4.7.jar
JavaSE 1.8
Eclipse 4.14.0
構文
1.Properties にはメールサーバに接続します
//Propertiesにはメールサーバに接続する
Properties 変数名 = new Properties();
// SMTP プロトコルによるメールの送信
変数名.put(“mail.transport.protcol", “smtp");
//メールサーバーのホストの設定
変数名.put(“mail.smtp.host", host);
2.Sessionを作成します
Session session = Session.getInstance(Propertiesの変数名, null);
3.宛先(To)の設定
Message msg = new MimeMessage(セッション変数名); msg.setRecipients(Message.RecipientType.TO, InternetAddressの宛先(To)変数名);
4.宛先(CC)の設定
Message msg = new MimeMessage(セッション変数名); msg.setRecipients(Message.RecipientType.CC, InternetAddressの宛先(CC)変数名);
使用例
package com.arkgame.study;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSendInfo {
public static void main(String[] args) {
// 宛先(To)
String to = "testa@arkgame.com";
// 宛先(Cc)
String cc = "testb@arkgame.com";
// 送信者(From)
String from = "testc@arkgame.com";
// smtpサーバ
String host = "smtp.arkgame.com";
//Propertiesにはメールサーバに接続する
Properties pt = new Properties();
pt.put("mail.transport.protcol", "smtp");
//メールサーバーのホストの設定
pt.put("mail.smtp.host", host);
Session session = Session.getInstance(pt, null);
try {
Message msg = new MimeMessage(session);
//送信元の設定
msg.setFrom(new InternetAddress(from));
InternetAddress[] toAddr = { new InternetAddress(to) };
InternetAddress[] ccAddr = { new InternetAddress(cc) };
// 宛先(To)の設定
msg.setRecipients(Message.RecipientType.TO, toAddr);
// 宛先(CC)の設定
msg.setRecipients(Message.RecipientType.CC, ccAddr);
// 件名の設定
msg.setSubject("送信成功のお知らせ");
msg.setSentDate(new Date());
// 本文の設定
msg.setText("送信の本文テスト123");
//メールの送信
javax.mail.Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}