LoginSignup
7
9

More than 5 years have passed since last update.

Java SMTPSで認証・暗号化してメール送信(本文+添付ファイル)

Last updated at Posted at 2016-02-09

はじめに

SMTPSでメールアカウントを認証してから暗号化してメール送信します。
ついでに本文と添付ファイルの構成例とします。

事前に以下のライブラリを用意します。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。

SMTPSTest.java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
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;
import javax.mail.util.ByteArrayDataSource;

/**
 *
 * @author tool-taro.com
 */
public class SMTPSTest {

    public static void main(String[] args) throws MessagingException, IOException {

        String from = "差出人メールアドレス";
        String fromName = "差出人名を指定します";
        String subject = "件名を指定します";
        String to = "宛先メールアドレス";
        String toName = "宛名を指定します";
        String body = "これは本文です。\n\n\n\n\n\n\n\n\n\n以上。";
        String attachmentFileName = "添付ファイル名.txt";
        String attachmentFileType = "text/plain; charset=UTF-8";
        byte[] attachmentFileBody = "これは添付ファイルです。\n\n\n\n\n\n\n\n\n\n以上。".getBytes("UTF-8");

        String host = "メール送信サーバホスト";
        String user = "メール送信アカウント";
        String password = "メール送信アカウントパスワード";

        Properties properties;
        Session session;
        Store store = null;
        Transport transport = null;
        MimeMessage mimeMessage;
        MimeBodyPart messageBody;
        MimeMultipart multipart;
        InternetAddress[] address;

        try {
            properties = System.getProperties();
            properties.setProperty("mail.transport.protocol", "smtps");
            properties.setProperty("mail.smtp.port", "465");
            properties.setProperty("mail.smtp.auth", "true");
            properties.setProperty("mail.smtp.starttls.enable", "true");
            properties.setProperty("mail.smtp.starttls.required", "true");
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.smtp.socketFactory.fallback", "true");

            session = Session.getInstance(properties);

            mimeMessage = new MimeMessage(session);
            //件名は(一応)JISで
            mimeMessage.setSubject(MimeUtility.encodeText(subject, "iso-2022-jp", "B"), "iso-2022-jp");
            mimeMessage.setSentDate(new Date());

            address = new InternetAddress[1];
            address[0] = new InternetAddress(from);
            //差出人名は設定しなくても問題ない
            if (fromName != null) {
                //差出人名は(一応)JISで
                address[0].setPersonal(MimeUtility.encodeText(fromName, "iso-2022-jp", "B"));
            }
            mimeMessage.setFrom(address[0]);

            address[0] = new InternetAddress(to);
            //宛名は設定しなくても問題ない
            if (toName != null) {
                //宛名は(一応)JISで
                address[0].setPersonal(MimeUtility.encodeText(toName, "iso-2022-jp", "B"));
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, address);

            /*
                マルチパートのメッセージを作成する
                構造
                    パート1: 本文
                    パート2: 添付ファイル
             */
            multipart = new MimeMultipart();
            mimeMessage.setContent(multipart);

            //パート1: 本文
            messageBody = new MimeBodyPart();
            //本文のテキストは(一応)JISで
            messageBody.setText(body, "iso-2022-jp");
            messageBody.setHeader("Content-Transfer-Encoding", "7bit");
            multipart.addBodyPart(messageBody);

            //パート2: 添付ファイル
            messageBody = new MimeBodyPart();
            //添付ファイル名は(一応)JISで
            messageBody.setFileName(MimeUtility.encodeText(attachmentFileName, "iso-2022-jp", "B"));
            messageBody.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(attachmentFileBody), attachmentFileType)));
            multipart.addBodyPart(messageBody);

            transport = session.getTransport();
            transport.connect(host, user, password);
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        }
        finally {
            if (store != null) {
                try {
                    store.close();
                }
                catch (MessagingException e) {
                }
            }
            if (transport != null) {
                try {
                    transport.close();
                }
                catch (MessagingException e) {
                }
            }
        }
    }
}

動作確認

$ javac SMTPSTest.java
$ java SMTPSTest

送られてきたメールを見てみます。
無題.png
指定した通りの

  • 差出人名
  • 宛名
  • 件名
  • 本文
  • 添付ファイル名

が表示されています。

添付ファイルを開いてみます。
無題2.png
<<<<<<< HEAD

環境

=======

環境

YOUR_EDITION
- 開発
- Windows 10 Pro
- JDK 1.8.0_112
- NetBeans IDE 8.2

  • 動作検証
    • CentOS Linux release 7.2
    • JDK 1.8.0_112

Webツールも公開しています。
Web便利ツール@ツールタロウ

7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9