<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\SMTP; require 'path/to/PHPMailer/src/Exception.php'; require 'path/to/PHPMailer/src/PHPMailer.php'; require 'path/to/PHPMailer/src/SMTP.php'; function sendMail($to, $toname, $subject, $body) { // 文字エンコードを指定 mb_language('uni'); mb_internal_encoding('UTF-8'); $mail = new PHPMailer(true); try { //Enable SMTP debugging //SMTP::DEBUG_OFF = off (for production use) //SMTP::DEBUG_CLIENT = client messages //SMTP::DEBUG_SERVER = client and server messages $mail->SMTPDebug = SMTP::DEBUG_SERVER; $mail->isSMTP(); $mail->Host = SMTP_SERVER; $mail->SMTPAuth = true; $mail->Username = SMTP_USER; $mail->Password = SMTP_PASS; $mail->SMTPSecure = 'tls'; $mail->Port = SMTP_PORT; $mail->CharSet = "utf-8"; $mail->setFrom(FROM_MAIL, SITE_NAME); $mail->addAddress($to, $toname); //$mail->addReplyTo('info@example.com', 'Information'); //$mail->addCC('cc@example.com'); //$mail->addBCC('bcc@example.com'); //Attachments //$mail->addAttachment('/var/tmp/file.tar.gz'); //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $body; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } } ?>
Fatal error: Uncaught Error: Class "SMTP" not found
use PHPMailer\PHPMailer\SMTP;
SMTPプロトコルを使用してメールを送信することができ、メッセージの配信可能性が向上します。また、SMTPクラスを使用することで、エラーハンドリングやデバッグ機能も利用できるようになり、問題が発生した際の原因特定が容易になります。
SMTP の暗号化方式は 使用するポート番号とセットで決まるのが基本です。
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mail->Port = 465;
PHPMailerで外部のメールサーバー(SMTPサーバー)を使う場合、自分のサーバーにメール送信機能は一切なくても問題ありません。PHPMailerは「メールを送るプログラム」ではなく、
外部のSMTPサーバーへ接続してメール送信を依頼するクライアントです。
つまり、あなたのサーバーはただの「PHPが動く場所」であればよく、
メール送信の実務はすべて外部SMTPサーバーが担当します。あなたのサーバー側には sendmail も postfix も不要です。
但し、外向きSMTPがブロックされていることもあります。その場合、2525番ポートでSMTP送信が可能なサービスなどを検討する。
OpenSSL で SMTP サーバーに直接接続できるか確認する
openssl s_client -starttls smtp -connect smtp.example.com:587
openssl s_client -connect smtp.example.com:465
成功する場合
大量の証明書情報が表示される
最後に 250 STARTTLS や 220 などの応答が返る
失敗する場合
Connection timed out(ポートが塞がれている)
Connection refused(相手が拒否)
何も返らず固まる(アウトバウンド制限)