このトピックでは、PHP 関数を構築し、その関数を呼び出して SMTP 経由でメールを送信する方法について説明します。
PHP を使用して SMTP 経由でメールを送信する呼び出し例
方法 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://smtp.sg.aliyun.com'; // メールサーバーアドレス
$mail->Port = 465; // ポート番号。
//$mail->Host = 'smtp.sg.aliyun.com';
//$mail->Port = 25;
$mail->SMTPAuth = true; // 権限を付与します。
$mail->Username = 'a***@example.net'; // 送信アドレス
$mail->Password = '**********'; // SMTP パスワード。
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 暗号化を有効にします。
// 受信者
$mail->setFrom('a***@example.net, 'Mailer'); // 送信者アドレスを表示します。
$mail->addAddress('test1***@example.net,'a***@example.net'); // 受信者とニックネーム。
//$mail->addAddress('test1***@example.net'); // ニックネームは必須ではありません。
$mail->addReplyTo('a***@example.net, 'Information');// 返信先アドレス。
$mail->addCC('test2***@example.net');// CC。
$mail->addBCC('test3***@example.net');// BCC。
// 添付ファイル
//$mail->addAttachment('C:/Users/Documents/test.jpg'); // 添付ファイルを追加します。
//$mail->addAttachment ('new.jpg, C:/Users/Documents/test.jpg); // 名前はオプションです。
// コンテンツ
$mail->isHTML(true); // HTML 形式。
$mail->Subject = 'テストタイトル';
$mail->Body = 'テストコンテンツ';
//$mail->AltBody = 'これは、HTML メールクライアントではないクライアント向けのプレーンテキストの本文です。';
$mail->Sender = 'a***@example.net';
echo 'メッセージが送信されました';
$mail->send();
echo 'メッセージが送信されました';
} catch (Exception $e) {
echo "メッセージを送信できませんでした。Mailer エラー: {$mail->ErrorInfo}";
}
?>方法 2: 外部依存関係 email.class.php を使用します
<?php
require 'email.class.php';
$mailto='受信者アドレス';
$mailsubject="テストメール";
$mailbody='メールコンテンツ';
$smtpserver = "smtp.sg.aliyun.com";
$smtpserverport = 25;
// $smtpserver= "ssl://smtp.sg.aliyun.com";
// $smtpserverport = 465;
$smtpusermail = "送信者アドレス";
// test***@example.net などの送信者のアカウント。
$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";
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;
}
}
}
?>