すべてのプロダクト
Search
ドキュメントセンター

Direct Mail:SMTP Java 呼び出しの例

最終更新日:Nov 09, 2025

このトピックでは、JavaMail を使用して簡易メール転送プロトコル (SMTP) 経由でメールを送信する方法について説明します。

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>

サンプルコード:

package org.example;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
//import java.net.MalformedURLException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
//import java.util.HashMap;
//import java.util.Base64;
//import java.net.URL;
//import java.io.IOException;
//import java.io.InputStream;
//import javax.mail.util.ByteArrayDataSource;
//import java.net.URLEncoder;
//import javax.activation.DataHandler;
//import javax.activation.FileDataSource;
//import javax.activation.URLDataSource;

//import com.google.gson.GsonBuilder;

public class SampleMail {
    // 定数を構成します。
    private static final String SMTP_HOST = "smtpdm.aliyun.com";
    private static final int SMTP_PORT = 80;
    private static final String USER_NAME = "送信元アドレス";
    private static final String PASSWORD = "xxxxxxx";

    protected static String genMessageID(String mailFrom) {
        // Message-ID を生成します。
        if (!mailFrom.contains("@")) {
            throw new IllegalArgumentException("無効なメールフォーマット: " + mailFrom);
        }
        String domain = mailFrom.split("@")[1];
        UUID uuid = UUID.randomUUID();
        return "<" + uuid.toString() + "@" + domain + ">";
    }

    private static void setRecipients(MimeMessage message, Message.RecipientType type, String[] recipients)
            throws MessagingException {
        // 受信者アドレスを設定します。
        if (recipients == null || recipients.length == 0) {
            return; // リストが空の場合は設定しません。
        }
        InternetAddress[] addresses = new InternetAddress[recipients.length];
        for (int h = 0; h < recipients.length; h++) {
            addresses[h] = new InternetAddress(recipients[h]);
        }
        message.setRecipients(type, addresses);
    }

    public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
        // メールを送信するための環境プロパティを構成します。
        final Properties props = new Properties();

        // SMTP でメールを送信するには ID 検証が必要であることを指定します。
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        // ポートを設定します。
        props.put("mail.smtp.port", SMTP_PORT);// または "25"。SSL を使用する場合は、ポート 80 または 25 の構成を削除し、次の構成を使用します。
        // 暗号化メソッド。
        //props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        //props.put("mail.smtp.socketFactory.fallback", "false");// 暗号化されていない接続へのバックオフを無効にします。
        //props.put("mail.smtp.socketFactory.port", "465");
        //props.put("mail.smtp.port", "465");

        props.put("mail.smtp.from", USER_NAME);    // mailfrom パラメーター。
        props.put("mail.user", USER_NAME);// 送信者のアカウント。これはコンソールで作成された送信元アドレスです。
        props.put("mail.password", PASSWORD);// 送信元アドレスの SMTP パスワード。このパスワードはコンソールで送信元アドレスに設定します。
        //props.put("mail.smtp.connectiontimeout", 1000);
        System.setProperty("mail.mime.splitlongparameters", "false");// 添付ファイル名が長すぎることによる表示の問題を解決します。
        //props.setProperty("mail.smtp.ssl.enable", "true");  // ポート 465 でこれを使用します。

        // SMTP ID 検証のための権限付与情報を構築します。
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USER_NAME, PASSWORD);
            }
        };

        // 環境プロパティと権限付与情報を使用してメールセッションを作成します。
        Session mailSession = Session.getInstance(props, authenticator);

        String messageIDValue = genMessageID(USER_NAME);
        MimeMessage message = new MimeMessage(mailSession) {
            @Override
            protected void updateMessageID() throws MessagingException {
                setHeader("Message-ID", messageIDValue);
            }
        };

        try {
            // 送信者のメールアドレスとニックネームを設定します。コンソールで構成した送信元アドレスを入力します。このアドレスは mail.user の値と同じである必要があります。ニックネームはカスタマイズできます。
            InternetAddress from = new InternetAddress(USER_NAME, "送信者のニックネーム");// from パラメーター。これにより、別のアドレスに代わってメールを送信できます。注: 別のアドレスに代わって送信されたメールは、受信者に拒否されるか、迷惑メールフォルダに移動される可能性があります。
            message.setFrom(from);

            setRecipients(message, Message.RecipientType.TO, new String[]{"recipient_address_1", "recipient_address_2"});
            setRecipients(message, Message.RecipientType.CC, new String[]{"recipient_address_3", "recipient_address_4"});
            setRecipients(message, Message.RecipientType.BCC, new String[]{"recipient_address_5", "recipient_address_6"});

            InternetAddress replyToAddress = new InternetAddress("reply_to_address");
            message.setReplyTo(new Address[]{replyToAddress});// オプション。返信先アドレスを設定します。
            message.setSentDate(new Date());
            message.setSubject("テスト件名");
//            message.setContent("テスト TXT コンテンツ 1", "text/text;charset=UTF-8");// プレーンテキストコンテンツ。MimeBodyPart を使用すると上書きされます。
//            または
//            message.setContent("テスト<br> HTML コンテンツ 2", "text/html;charset=UTF-8");// HTML コンテンツ。MimeBodyPart を使用すると上書きされます。

//            // メールトラッキングサービスを有効にするには、次のコードを使用してトラッキングリンクヘッダーを設定します。前提条件と制約については、「データ追跡機能を有効にする方法」をご参照ください。
//            String tagName = "tagname4";
//            HashMap<String, String> trace = new HashMap<>();
//            // これは文字列 "1" です。
//            trace.put("OpenTrace", "1");      // メールの開封トラッキングを有効にします。
//            trace.put("LinkTrace", "1");     // メール内の URL クリックトラッキングを有効にします。
//            trace.put("TagName", tagName);   // コンソールで作成されたタグ名。
//            String jsonTrace = new GsonBuilder().setPrettyPrinting().create().toJson(trace);
//            //System.out.println(jsonTrace);
//            String base64Trace = new String(Base64.getEncoder().encode(jsonTrace.getBytes()));
//            // トラッキングリンクヘッダーを設定します。
//            message.addHeader("X-AliDM-Trace", base64Trace);
            // 元の EML ファイルのサンプル値: X-AliDM-Trace: eyJUYWdOYW1lIjoiVGVzdCIsIk9wZW5UcmFjZSI6IjEiLCJMaW5rVHJhY2UiOiIxIn0=

            // 添付ファイルとコンテンツを送信します。
            // マルチパートメッセージを作成します。
            Multipart multipart = new MimeMultipart();

//            // プレーンテキストコンテンツ用の BodyPart を作成します。
//            BodyPart textPart = new MimeBodyPart();
//            textPart.setText("テスト TXT コンテンツ 3");
//            multipart.addBodyPart(textPart);

            // HTML コンテンツ用の BodyPart を作成します。
            BodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent("テスト<br> HTML コンテンツ 4", "text/html;charset=UTF-8");// メールのコンテンツを設定します。これにより、以前の message.setContent 呼び出しが上書きされます。
            multipart.addBodyPart(htmlPart);

//            // 添付ファイルセクション。
//            // 添付ファイルを送信します。メールの合計サイズは 15 MB を超えることはできません。メッセージパートを作成します。
//            // ローカルの添付ファイルを送信します。
//            String[] fileList = {"C:\\Users\\Downloads\\test1.txt", "C:\\Users\\Downloads\\test2.txt"};
//            for (String filePath : fileList) {
//                MimeBodyPart mimeBodyPart = new MimeBodyPart();
//
//                FileDataSource fileDataSource = new FileDataSource(filePath);
//                mimeBodyPart.setDataHandler(new DataHandler(fileDataSource));
//                // ファイルパスを含む中国語の添付ファイル名での文字化けを処理します。
//                mimeBodyPart.setFileName(MimeUtility.encodeWord(fileDataSource.getName()));
//                mimeBodyPart.addHeader("Content-Transfer-Encoding", "base64");
//                multipart.addBodyPart(mimeBodyPart);
//            }


//            // URL 添付ファイルを送信します。
//            String[] fileListUrl = {"https://example.oss-cn-shanghai.aliyuncs.com/xxxxxxxxxxx1.png", "https://example.oss-cn-shanghai.aliyuncs.com/xxxxxxxxxxx2.png"};
//            for (String fileUrl : fileListUrl) {
//                URL url = new URL(fileUrl);
//                String filename = url.getPath();
//                filename = filename.substring(filename.lastIndexOf('/') + 1);
//                try (InputStream in = url.openStream()) {
//                    // 添付ファイルパートを作成します。
//                    MimeBodyPart attachmentPart = new MimeBodyPart();
//                    // バイト配列データソースを使用します。
//                    ByteArrayDataSource ds = new ByteArrayDataSource(in, "application/octet-stream");
//                    attachmentPart.setDataHandler(new javax.activation.DataHandler(ds));
//                    attachmentPart.setFileName(filename);
//                    attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT);
//                    multipart.addBodyPart(attachmentPart);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            }

            // 完全なメッセージを追加します。
            message.setContent(multipart);
            // 添付ファイル送信コードの終わり。

            //mailSession.setDebug(true);// デバッグモードを有効にします。
            Transport.send(message);
            System.out.println("正常に送信されました!");
        } catch (MessagingException | UnsupportedEncodingException e) {
            System.err.println("メールの送信に失敗しました: " + e.getMessage());
            e.printStackTrace();
//        } catch (MalformedURLException e) {
//            throw new RuntimeException(e);
        }

    }

}