Shammer's Philosophy

My private adversaria

Java Mail CC 送信 Sample

Java Mail Sample - Shammerismの内容に CC 送信処理を追加しただけだが。CC 送信するには、javax.mail.internet.InternetAddress の配列をもう一つ用意し、javax.mail.Message.setRecipients で Message.RecipientType.CC として渡す。

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 JavaMail {
    public static void main(String[]args){
	String to = "sampleTO@sample.com";
	String cc = "sampleCC@sample.com";
	String from = "sampleFROM@sample.com";
	String host = "smtp.sample.com";
	String date = new Date().toString();

	Properties p = new Properties();
	p.put("mail.transport.protocol", "smtp");
	p.put("mail.smtp.host", host);

	Session session = Session.getInstance(p, null);
	try {
	    Message message = new MimeMessage(session);
	    message.setFrom(new InternetAddress(from));
	    InternetAddress[] toAddress = {new InternetAddress(to)};
	    InternetAddress[] ccAddress = {new InternetAddress(cc)};
	    message.setRecipients(Message.RecipientType.TO, toAddress);
	    message.setRecipients(Message.RecipientType.CC, ccAddress);
	    message.setSubject("Test");
	    message.setSentDate(new Date());
	    message.setText("This is a test.");
	    javax.mail.Transport.send(message);
	}
	catch(Exception e){
	    e.printStackTrace();
	}
    }
}