// [SendAttachmentSample.java]
// 添付ファイル付きメッセージの送信を行うサンプルプログラム
import java.io.IOException;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import com.sk_jp.mail.SimpleSender;

public class SendAttachmentSample {
    public static void main(String[] args) throws Exception {
        String host = args[0];
        String to   = args[1];
        String from = args[2];
        String subject = "テストメッセージです";

        SimpleSender sender = new SimpleSender();
        MimeMessage msg = sender.createMessage();

///////////////////////////////////////////////////// メッセージの編集(1)
        SimpleSender.setHeaders(msg, to, from);
        msg.setSubject(subject, "ISO-2022-JP");

        msg.setContent(createAttachmentPart());
        msg.saveChanges();
/////////////////////////////////////////////////////

        sender.connect(host);
        sender.send(msg);
        sender.disconnect();
    }

    public static MimeMultipart createAttachmentPart()
                throws MessagingException, IOException {
        String text = "テキストファイルを添付しています。";
        String filename = "test.txt";

        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(text, "ISO-2022-JP");

        MimeBodyPart filePart = new MimeBodyPart();
        filePart.setDataHandler(new DataHandler(new FileDataSource(filename)));
        // デフォルトではContent-Disposition:はattachmentになります。
        filePart.setFileName(filename);
//      com.sk_jp.mail.MailUtility.setFileName(
//              filePart, filename, "ISO-2022-JP", null);

        // デフォルトはmultipart/mixedになります。
        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(textPart);
        mp.addBodyPart(filePart);

        return mp;
    }
}

