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

Direct Mail:SMTP の PHP 呼び出し例

最終更新日:Nov 09, 2025

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

SMTP プロトコル経由で PHP を使用してメールを送信する

方法 1:外部依存関係 phpmailer を使用します。 GitHub から次のファイルをダウンロードできます:PHPMailer.php、Exception.php、および SMTP.php。

PHPMailer.php の中国語エンコーディングを変更します:

public $CharSet = self::CHARSET_ISO88591;

以下に変更します:

public $CharSet = self::CHARSET_UTF8;

メール送信のサンプルコード:

<?php
require 'PHPMailer.php';
require 'Exception.php';
require 'SMTP.php';


$mail = new PHPMailer(true);

try {
    //サーバー設定
    $mail->CharSet='UTF-8';
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      
    $mail->isSMTP();                                            
    $mail->Host       = 'ssl://smtpdm.aliyun.com';                     //Direct Mail サーバー
    $mail->Port       = 465;                                    //ポート
    //$mail->Host       = 'smtpdm.aliyun.com';                     
    //$mail->Port       = 80;  
    //$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //暗号化を有効にする                                  
    $mail->SMTPAuth   = true;                                   //認証
    $mail->Username   = 'test***@example.net';                     //送信元アドレス
    $mail->Password   = '*******';                               //SMTP パスワード
    //受信者
    $mail->setFrom('test***@example.net', 'Mailer');   //表示する送信元アドレス。別のアドレスに代わって送信するように設定できます。
    $mail->addAddress('test1***@example.net', 'name');     //受信者とニックネーム
    //$mail->addAddress('test1***@example.net');               //ニックネームはオプションです。
    //$mail->addAddress('test2***@example.net', 'name2');//複数の受信者を追加するには、別の行を追加します。
    $mail->addReplyTo('test1***@example.net', 'Information');//返信先アドレス
    $mail->addCC('test2***@example.net');//CC 受信者
    $mail->addBCC('test3***@example.net');//BCC 受信者

    	// // JSON
	// $createJson = [
	// 	"Version" => "1.0",
	// 	"Unsubscribe" => [
	// 		"LinkType" => "default",       // デフォルトポリシー
	// 		"FilterLevel" => "mailfrom_domain" // メールドメインレベルでフィルター
	// 	],
	// 	"OutboundIp" => [
	// 		"IpPoolId" => "exxxxxxe-4xx0-4xx3-8xxa-7xxxxxxxxxxxxf" // これを IP プール ID に置き換えます
	// 	]
	// ];

	// // JSON 文字列に変換
	// $jsonString = json_encode($createJson, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

	// // Base64 エンコーディング
	// $base64Trace = base64_encode($jsonString);

	// // カスタムメッセージヘッダーを追加
	// $mail->addCustomHeader('X-AliDM-Settings', $base64Trace);
    //添付ファイル
    //$mail->addAttachment('C:/Users/Documents/test.jpg');         //添付ファイルを追加
    $mail->addAttachment('C:/Users/Documents/test.jpg', 'new.jpg');    //名前はオプションです。

    //内容
    $mail->isHTML(true);                                  //HTML フォーマット
    $mail->Subject = '件名テスト';
    $mail->Body    = 'テスト内容';
    //$mail->AltBody = 'これは、HTML 形式に対応していないメールクライアント向けのプレーンテキストの本文です';

    $mail->Sender = 'test***@example.net';
    echo 'メッセージが送信されました';
    $mail->send();
    echo 'メッセージが送信されました';
} catch (Exception $e) {
    echo "メッセージを送信できませんでした。メーラーエラー: {$mail->ErrorInfo}";
}
?>

方法 2:外部依存関係 email.class.php を使用します

<?php
require 'email.class.php';

$mailto='Recipient address'; //受信者アドレス
$mailsubject="Test email"; //テストメール
$mailbody='This is the email content'; //これはメールのコンテンツです

$smtpserver     = "smtpdm.aliyun.com";
$smtpserverport = 80;
// $smtpserver= "ssl://smtpdm.aliyun.com";
// $smtpserverport = 465;
$smtpusermail   = "Sender address"; //送信者アドレス

// The sender's account, enter the sender address configured in the console, such as test***@@example.net //送信者のアカウント。コンソールで設定された送信者アドレス(例:test***@@example.net)を入力します
$smtpuser       = "Sender account"; //送信者アカウント
// The password required when accessing the SMTP service (set in the console by selecting the sender address) //SMTP サービスにアクセスするときに必要なパスワード(コンソールで送信者アドレスを選択して設定します)
$smtppass       = "***";

$mailsubject    = "=?UTF-8?B?" . base64_encode($mailsubject) . "?=";
$mailtype       = "HTML";

//Optional, set reply-to address //オプション。返信先アドレスを設定します
$smtpreplyto    = "***";

$smtp           = new smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass);
$smtp->debug    = false;
$cc   ="";
$bcc  = "";
$additional_headers = "";
//Set the sender name, users can customize the name. //送信者名を設定します。ユーザーは名前をカスタマイズできます。
$sender  = "Sender"; //送信者
$smtp->sendmail($mailto,$smtpusermail, $mailsubject, $mailbody, $mailtype, $cc, $bcc, $additional_headers, $sender, $smtpreplyto);
?>

email.class.php の内容を変更する必要があります

$header .="Reply-To: ".$replyToAddress."\r\n";//ここで、$replyToAddress はパラメーター $smtpreplyto です

  • email.class.php は外部依存関係です。インターネットから自分でダウンロードする必要があります。

  • mailto:受信者のメールアドレス。

  • smtpuser:完全な送信者アドレス。

email.class.php 参照例

<?php

/**
 * email smtp (php7 をサポート)
 *
 */


class Smtp
{
    /* パブリック変数 */
    public $smtp_port;

    public $time_out;

    public $host_name;

    public $log_file;

    public $relay_host;

    public $debug;

    public $auth;

    public $user;

    public $pass;

    /* プライベート変数 */
    private $sock;

    /* コンストラクター */
    function __construct($relay_host = "", $smtp_port = 80,$auth = false,$user,$pass)
    {
        $this->debug = FALSE;

        $this->smtp_port = $smtp_port;

        $this->relay_host = $relay_host;

        $this->time_out = 30; //fsockopen() で使用


        $this->auth = $auth;//認証

        $this->user = $user;

        $this->pass = $pass;


        $this->host_name = "localhost"; //HELO コマンドで使用
        $this->log_file = "";

        $this->sock = FALSE;

    }

    /* メイン関数 */

    function sendmail($to, $from, $subject, $body, $mailtype, $cc, $bcc, $additional_headers, $fromUser, $replyToAddress)
    {

        $mail_from = $this->get_address($this->strip_comment($from));

        $body = preg_replace("/(^|(\r\n))(\.)/", "\1.\3", $body);

        $header = "MIME-Version:1.0\r\n";

        if($mailtype=="HTML"){

            $header .= "Content-Type:text/html; charset=utf-8\r\n";

        }

        $header .= "To: ".$to."\r\n";

        if ($cc != "") {

            $header .= "Cc: ".$cc."\r\n";

        }

        $header .= "From: $fromUser<".$from.">\r\n";

        $header .= "Subject: ".$subject."\r\n";

        $header .= "Reply-To: ".$replyToAddress."\r\n";

        $header .= $additional_headers;

        $header .= "Date: ".date("r")."\r\n";

        $header .= "X-Mailer:By Redhat (PHP/".phpversion().")\r\n";

        list($msec, $sec) = explode(" ", microtime());

        $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">\r\n";

        // メールトラッキング機能を有効にするには、次のコードを使用してメッセージヘッダーにトラッキングリンクを設定します。前提条件と制約の詳細については、「データ追跡機能を有効にする」をご参照ください。
        //$header .= "Content-Transfer-Encoding: quoted-printable\r\n";
        //$header .= "X-AliDM-Trace: ". base64_encode(json_encode(['TagName'=>'user_created_tag','OpenTrace'=>"1"]))."\r\n";
        $TO = explode(",", $this->strip_comment($to));

        if ($cc != "") {

            $TO = array_merge($TO, explode(",", $this->strip_comment($cc)));

        }

        if ($bcc != "") {

            $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));

        }

        $sent = TRUE;

        foreach ($TO as $rcpt_to) {

            $rcpt_to = $this->get_address($rcpt_to);

            if (!$this->smtp_sockopen($rcpt_to)) {

                $this->log_write("エラー: ".$rcpt_to." にメールを送信できません\n");

                $sent = FALSE;

                continue;

            }

            if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {

                $this->log_write("メールが <".$rcpt_to."> に送信されました\n");

            } else {

                $this->log_write("エラー: <".$rcpt_to."> にメールを送信できません\n");

                $sent = FALSE;

            }

            fclose($this->sock);

            $this->log_write("リモートホストから切断されました\n");

        }

        return $sent;

    }

    /* プライベート関数 */

    function smtp_send($helo, $from, $to, $header, $body = "")
    {

        if (!$this->smtp_putcmd("HELO", $helo)) {

            return $this->smtp_error("HELO コマンドを送信しています");

        }

        //認証
        if($this->auth){

            if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {

                return $this->smtp_error("HELO コマンドを送信しています");

            }

            if (!$this->smtp_putcmd("", base64_encode($this->pass))) {

                return $this->smtp_error("HELO コマンドを送信しています");

            }

        }


        if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {

            return $this->smtp_error("MAIL FROM コマンドを送信しています");

        }

        if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {

            return $this->smtp_error("RCPT TO コマンドを送信しています");

        }

        if (!$this->smtp_putcmd("DATA")) {

            return $this->smtp_error("DATA コマンドを送信しています");

        }

        if (!$this->smtp_message($header, $body)) {

            return $this->smtp_error("メッセージを送信しています");

        }

        if (!$this->smtp_eom()) {

            return $this->smtp_error("<CR><LF>.<CR><LF> [EOM] を送信しています");

        }

        if (!$this->smtp_putcmd("QUIT")) {

            return $this->smtp_error("QUIT コマンドを送信しています");

        }

        return TRUE;

    }

    function smtp_sockopen($address)
    {

        if ($this->relay_host == "") {

            return $this->smtp_sockopen_mx($address);

        } else {

            return $this->smtp_sockopen_relay();

        }

    }

    function smtp_sockopen_relay()
    {

        $this->log_write("".$this->relay_host.":".$this->smtp_port." に接続しようとしています\n");

        $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);

        if (!($this->sock && $this->smtp_ok())) {

            $this->log_write("エラー: リレーホスト ".$this->relay_host." に接続できません\n");

            $this->log_write("エラー: ".$errstr." (".$errno.")\n");

            return FALSE;

        }

        $this->log_write("リレーホスト ".$this->relay_host." に接続しました\n");

        return TRUE;

    }

    function smtp_sockopen_mx($address)
    {

        $domain = preg_replace("/^.+@([^@]+)$/", "\1", $address);

        if (!@getmxrr($domain, $MXHOSTS)) {

            $this->log_write("エラー: MX \"".$domain."\" を解決できません\n");

            return FALSE;

        }

        foreach ($MXHOSTS as $host) {

            $this->log_write("".$host.":".$this->smtp_port." に接続しようとしています\n");

            $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);

            if (!($this->sock && $this->smtp_ok())) {

                $this->log_write("警告: mx ホスト ".$host." に接続できません\n");

                $this->log_write("エラー: ".$errstr." (".$errno.")\n");

                continue;

            }

            $this->log_write("mx ホスト ".$host." に接続しました\n");

            return TRUE;

        }

        $this->log_write("エラー: いずれの mx ホスト (".implode(", ", $MXHOSTS).") にも接続できません\n");

        return FALSE;

    }

    function smtp_message($header, $body)
    {

        fputs($this->sock, $header."\r\n".$body);

        $this->smtp_debug("> ".str_replace("\r\n", "\n"."> ", $header."\n> ".$body."\n> "));

        return TRUE;

    }

    function smtp_eom()
    {

        fputs($this->sock, "\r\n.\r\n");

        $this->smtp_debug(". [EOM]\n");

        return $this->smtp_ok();

    }

    function smtp_ok()
    {

        $response = str_replace("\r\n", "", fgets($this->sock, 512));

        $this->smtp_debug($response."\n");

        if (!preg_match("/^[23]/", $response)) {

            fputs($this->sock, "QUIT\r\n");

            fgets($this->sock, 512);

            $this->log_write("エラー: リモートホストが \"".$response."\" を返しました\n");

            return FALSE;

        }

        return TRUE;

    }

    function smtp_putcmd($cmd, $arg = "")
    {

        if ($arg != "") {

            if($cmd=="") $cmd = $arg;

            else $cmd = $cmd." ".$arg;

        }

        fputs($this->sock, $cmd."\r\n");

        $this->smtp_debug("> ".$cmd."\n");

        return $this->smtp_ok();

    }

    function smtp_error($string)
    {

        $this->log_write("エラー: ".$string." 中にエラーが発生しました。\n");

        return FALSE;

    }

    function log_write($message)
    {

        $this->smtp_debug($message);

        if ($this->log_file == "") {

            return TRUE;

        }

        $message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;

        if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {

            $this->smtp_debug("警告: ログファイル \"".$this->log_file."\" を開けません\n");

            return FALSE;

        }

        flock($fp, LOCK_EX);

        fputs($fp, $message);

        fclose($fp);


        return TRUE;

    }


    function strip_comment($address)
    {

        $comment = "/\([^()]*\)/";

        while (preg_match($comment, $address)) {

            $address = preg_replace($comment, "", $address);

        }

        return $address;

    }


    function get_address($address)
    {

        $address = preg_replace("/([ \t\r\n])+/", "", $address);

        $address = preg_replace("/^.*<(.+)>.*$/", "\1", $address);

        return $address;

    }

    function smtp_debug($message)
    {

        if ($this->debug) {

            echo $message;

        }

    }

}
?>