1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
public class JavaSmtp {
public static void main(String args[]) {
try {
// SMTPサーバへのsessionを生成する
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
Session session = Session.getDefaultInstance(props, null);
// MimeMessageを生成する
MimeMessage msg = new MimeMessage(session);
// MimeMessageへ送信者を設定
msg.setFrom(new InternetAddress("sender@example.com"));
// MimeMessageへ受信者を設定
msg.setRecipients(Message.RecipientType.TO,
new InternetAddress("recipient@example.com"));
// MimeMessageへ件名を設定
msg.setSubject("JavaMail:添付メール送信", "iso-2022-jp");
//// MimeMessageへ本文を設定
//msg.setText("このメールはプレーンなテキストメールです。", "ISO-2022-JP");
// 複数のボディを格納するマルチパートオブジェクトを生成
MimeMultipart content = new MimeMultipart();
// 1つ目のボディパートを作成し、本文を設定
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(
"このメールにはファイルが添付されています。",
"text/plain; charset=\"iso-2022-jp\"");
content.addBodyPart(textPart);
// 2つ目(以降)のボディパートを作成し、添付ファイルを設定
MimeBodyPart filePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("/tmp/example.bin");
DataHandler dh = new DataHandler(fds);
filePart.setDataHandler(dh);
filePart.setFileName(fds.getName());
content.addBodyPart(filePart);
// マルチパートオブジェクトを設定
msg.setContent(content);
// 送信する
Transport.send(msg);
} catch (SendFailedException e) {
// 送信失敗の場合
System.out.println("メール送信に失敗しました");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
最終更新時間:2008年11月17日 23時53分00秒 指摘や意見などあればSandBoxのBBSへ。