PHPMailerを使い、SMTP経由でのメール送信を実装します。 今回はGmailのSMTPサーバーを使いご紹介します。
Gmail アプリパスワードが必要です。 取得方法は、以下の投稿をご確認ください。
composer require phpmailer/phpmailer
composer require vlucas/phpdotenv
composerを使って、PHPMailerと環境変数用のライブラリをインストールします。
GMAIL_APP_PASSWORD="取得したアプリパスワード"
※.envファイルは.gitignoreに設定してあることを忘れずに。
<?php
require './vendor/autoload.php';
use Dotenv\Dotenv;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$phpmailer = new PHPMailer(true);
$phpmailer->isSMTP();
$phpmailer->SMTPAuth = true;
$phpmailer->Host = 'smtp.gmail.com';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Port = '465';
$phpmailer->Username = 'xxx@gmail.com';
$phpmailer->Password = $_ENV["GMAIL_APP_PASSWORD"];
$phpmailer->CharSet = 'UTF-8';
$phpmailer->setFrom('xxx@gmail.com', 'Omori');
$phpmailer->addAddress('xxx@example.com');
$phpmailer->Subject = "タイトル";
$phpmailer->Body = "本文";
$phpmailer->send();
その他の項目は固定です。
このプログラムをWebサーバー上で実行、REST APIとして実行することで、メール送信機能を動かすことができます。 今回は簡易的に以下のようにコマンドライン上で送信確認しました。
php index.php
©Omori
MEOW!