【Java】 Java で、 Email を送るには... [2] ~ JavaMail / 添付ファイル付きメール編 ~

■ はじめに

https://blogs.yahoo.co.jp/dk521123/36230453.html
の続き。

今度は、添付ファイルを付けて送る。
ついでに、CCとBCCをつけてみた。

■ ポイント

 * 言葉で説明するより、サンプルコードをみてもらった方が早い...

「■ サンプル」部分より抜粋

BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(this.mailBody);
// ★「text/html;」→「text/plain;」でないと改行コードで折り返さなくなる★
// ★「charset=UTF-8」がないとBody部が文字化け★
messageBodyPart.setContent(this.mailBody, "text/plain; charset=UTF-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

// ★添付ファイルを設定★
if (this.attachmentFilePath != null) {
  MimeBodyPart mimeBodyPart = new MimeBodyPart();
  FileDataSource fileDataSource = new FileDataSource(this.attachmentFilePath);
  DataHandler dataHandler = new DataHandler(fileDataSource);
  mimeBodyPart.setDataHandler(dataHandler);
  mimeBodyPart.setFileName(MimeUtility.encodeWord(dataHandler.getName()));
  multipart.addBodyPart(mimeBodyPart);
}
mimeMessage.setContent(multipart);
Transport.send(mimeMessage);

■ サンプル

import java.io.UnsupportedEncodingException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class EmailHandler {
  private final static String DEFAULT_TIMEOUT = "10000";
  private final static String DEFAULT_HOST = "localhost";
  private final static String DEFAULT_POST = "25";
  private String fromAddress;
  private List<String> toAddresses;
  private List<String> ccAddresses;
  private List<String> bccAddresses;
  private String mailSubject;
  private String mailBody;
  private String attachmentFilePath; // ★注目★
  private String host;
  private String port;
  private String timeout;
  private boolean isOnDebugMode;

  /**
   * Default Contractor.
   */
  public EmailHandler() {
    this.fromAddress = null;
    this.toAddresses = new ArrayList<>();
    this.ccAddresses = new ArrayList<>();
    this.bccAddresses = new ArrayList<>();
    this.mailSubject = null;
    this.mailBody = null;
    this.attachmentFilePath = null;
    this.host = DEFAULT_HOST;
    this.port = DEFAULT_POST;
    this.timeout = DEFAULT_TIMEOUT;
    this.isOnDebugMode = false;
  }

  public void setFromAddress(String fromAddress) {
    this.fromAddress = fromAddress;
  }

  public void setToAddresses(List<String> toAddresses) {
    this.toAddresses = toAddresses;
  }

  public void addToAddress(String toAddress) {
    this.toAddresses.add(toAddress);
  }

  public void setCcAddresses(List<String> ccAddresses) {
    this.ccAddresses = ccAddresses;
  }

  public void addCcAddress(String ccAddress) {
    this.ccAddresses.add(ccAddress);
  }

  public void setBccAddresses(List<String> bccAddresses) {
    this.bccAddresses = bccAddresses;
  }

  public void addBccAddress(String bccAddress) {
    this.bccAddresses.add(bccAddress);
  }

  public void setMailSubject(String mailSubject) {
    this.mailSubject = mailSubject;
  }

  public void setMailBody(String mailBody) {
    this.mailBody = mailBody;
  }

  public void setAttachmentFilePath(String attachmentFilePath) {
    this.attachmentFilePath = attachmentFilePath;
  }

  public void setHost(String host) {
    this.host = host;
  }

  public void setPort(String port) {
    this.port = port;
  }

  public void setOnDebugMode(boolean isOnDebugMode) {
    this.isOnDebugMode = isOnDebugMode;
  }

  public void send() throws MessagingException, UnsupportedEncodingException {
    if (this.toAddresses == null || this.host == null) {
      throw new InvalidParameterException();
    }

    Properties props = new Properties();
    props.put("mail.smtp.host", this.host);
    props.put("mail.smtp.port", this.port);
    props.put("mail.debug", this.isOnDebugMode);
    props.put("mail.smtp.connectiontimeout", this.timeout);
    props.put("mail.smtp.timeout", this.timeout);

    Session session = Session.getInstance(props, null);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(this.toInternetAddress(this.fromAddress));

    InternetAddress[] toAddresses = this.toInternetAddresses(this.toAddresses);
    mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses);

    InternetAddress[] ccAddresses = this.toInternetAddresses(this.ccAddresses);
    mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses);

    InternetAddress[] bccAddresses = this.toInternetAddresses(this.bccAddresses);
    mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddresses);

    mimeMessage.setSubject(this.mailSubject);
    mimeMessage.setSentDate(new Date());

    // ★重要部分★
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(this.mailBody);
    messageBodyPart.setContent(this.mailBody, "text/plain; charset=UTF-8");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // ★添付ファイルを設定★
    if (this.attachmentFilePath != null) {
      MimeBodyPart mimeBodyPart = new MimeBodyPart();
      FileDataSource fileDataSource = new FileDataSource(this.attachmentFilePath);
      DataHandler dataHandler = new DataHandler(fileDataSource);
      mimeBodyPart.setDataHandler(dataHandler);
      mimeBodyPart.setFileName(MimeUtility.encodeWord(dataHandler.getName()));
      multipart.addBodyPart(mimeBodyPart);
    }
    mimeMessage.setContent(multipart);
    Transport.send(mimeMessage);
  }

  private InternetAddress[] toInternetAddresses(List<String> addresses) throws AddressException {
    InternetAddress[] returnValues = new InternetAddress[addresses.size()];

    int index = 0;
    for (String address : addresses) {
      returnValues[index] = this.toInternetAddress(address);
      index++;
    }

    return returnValues;
  }

  private InternetAddress toInternetAddress(String address) throws AddressException {
    return new InternetAddress(address);
  }

  /**
   * 【使用例】
   * 
   * @param args
   */
  public static void main(String[] args) {
    try {
      EmailHandler email = new EmailHandler();
      email.setFromAddress("sample@yahoo.com");
      email.addToAddress("to.sample@gmail.com");
      email.addCcAddress("cc.sample@gmail.com");
      email.addBccAddress("bcc.sample@gmail.com");
      email.setMailSubject("test");
      email.setMailBody("body");
      email.setOnDebugMode(true);
      email.setAttachmentFilePath("C:\\temp\\Book1.xlsx");
      email.send();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

■ 注意:Body部が表示されない場合

 * 以下の「サンプル(ダメな例)」だと、Body部が表示されない

サンプル(ダメな例)

    mimeMessage.setSubject(this.mailSubject);
    mimeMessage.setSentDate(new Date());
    mimeMessage.setText(this.mailBody);

    // ★添付ファイル処理★
    if (this.attachmentFilePath != null) {
      Multipart multipart = new MimeMultipart();
      MimeBodyPart mimeBodyPart = new MimeBodyPart();
      FileDataSource fileDataSource = new FileDataSource(this.attachmentFilePath);
      DataHandler dataHandler = new DataHandler(fileDataSource);
      mimeBodyPart.setDataHandler(dataHandler);
      mimeBodyPart.setFileName(MimeUtility.encodeWord(dataHandler.getName()));
      multipart.addBodyPart(mimeBodyPart);
      mimeMessage.setContent(multipart);
    }
    
    Transport.send(mimeMessage);
  }

参考文献

http://stackoverflow.com/questions/14547435/body-message-does-not-appear-when-sending-attachments
より抜粋

// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
messageBodyPart.setContent(body, "text/html");

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//Add the bodypart for the attachment(s)
// Send the complete message parts
message.setContent(multipart); //message is of type - MimeMessage


関連記事

Java で、 Email を送るには... [1] ~ JavaMail / テキストメール編 ~

https://blogs.yahoo.co.jp/dk521123/36230453.html