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

Direct Mail:SMTP-PHP

最終更新日:Jan 19, 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->SMTPAuth   = true;                                   // 権限を付与します。
    $mail->Username   = 'Sender@demo.aliyun.com';                     // 送信元アドレス。
    $mail->Password   = '*******';                               //SMTP パスワード。
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // 暗号化を有効にします。
    //受信者
    $mail->setFrom('Sender@demo.aliyun.com', 'Mailer');   // 表示される送信元アドレス。プロキシ送信者を設定することもできます。
    $mail->addAddress('Address@demo.aliyun.com', 'name');     // 受信者のメールアドレスとニックネーム。
    //$mail->addAddress('Address@demo.aliyun.com');               // ニックネームはオプションです。
    //$mail->addAddress('Address2@demo.aliyun.com', 'name2');// $mail->addAddress フィールドを追加して受信者を追加します。
    $mail->addReplyTo('Address@demo.aliyun.com', 'Information');// 返信先アドレス。
    $mail->addCC('Address@demo.aliyun.com');// CC フィールドのアドレス。
    $mail->addBCC('Address@demo.aliyun.com');// BCC フィールドのアドレス。

    //添付ファイル
    //$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 = 'Sender@demo.aliyun.com';
    $mail->send();
    echo 'メッセージが送信されました';
} catch (Exception $e) {
    echo "メッセージを送信できませんでした。Mailer エラー: {$mail->ErrorInfo}";
}
?>

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

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

$mailto='受信者アドレス';
$mailsubject="テストメール";
$mailbody='メールコンテンツ';

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

// 送信者のアカウント。コンソールで指定した送信者アドレスを入力します。例:xxx@xxx.com。
$smtpuser       = "送信者アカウント";
// SMTP へのアクセスに使用されるパスワード。コンソールで送信者アドレスを選択してパスワードを指定できます。
$smtppass       = "***";

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

// オプション。返信先アドレス。
$smtpreplyto    = "***";

$smtp           = new smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass);
$smtp->debug    = false;
$cc   ="";
$bcc  = "";
$additional_headers = "";
// 送信者の名前。必要に応じて名前を指定できます。
$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";

        // メール追跡機能を有効にする場合は、次のサンプルコードを使用して追跡用の SMTP ヘッダーを設定します。関連する前提条件と制限については、「データ追跡機能を有効にするにはどうすればよいですか?」を参照してください。
        //$header .= "Content-Transfer-Encoding: quoted-printable\r\n";
        //$header .= "X-AliDM-Trace: ". base64_encode(json_encode(['TagName'=>'カスタムタグ','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;

        }

    }

}
?>