- Home ›
- JavaMailでメール送信 ›
- 添付ファイルの送信 ›
- HERE
サンプルプログラム
広告
では今までの説明を踏まえて、実際にファイル添付してメールを送信するサンプルプログラムを見てみます。
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class msgsendsample{
static String msgText = "添付ファイルがあるメール送信サンプルです。";
public static void main(String[] args){
if (args.length != 5){
usage();
System.exit(1);
}
System.out.println();
String to = args[0];
String from = args[1];
String host = args[2];
String filename = args[3];
boolean debug = Boolean.valueOf(args[4]).booleanValue();
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.host", host);
props.put("mail.from", from);
if (debug){
props.put("mail.debug", args[4]);
}
Session session = Session.getInstance(props);
session.setDebug(debug);
try{
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = InternetAddress.parse(args[0]);
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("JavaMail APIs Test", "ISO-2022-JP");
msg.setSentDate(new Date());
/* 添付ファイルの処理 */
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(msgText, "ISO-2022-JP");
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(filename);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(MimeUtility.encodeWord(fds.getName()));
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
Transport.send(msg);
}catch(MessagingException mex){
System.out.println("¥n--Exception handling in msgsendsample.java");
mex.printStackTrace();
}catch(java.io.UnsupportedEncodingException uex){
}
}
private static void usage(){
System.out.println("usage: java msgsendsample <to> <from>
<smtp> <file> true|false");
}
}
( Written by Tatsuo Ikura )
JavaDrive