0
0

AWS Cloud9でメールを送る方法

Posted at

結論: SESを使え

「Cloud9 メール」でググると、Cloud9はGmailしか送れない、という情報が真っ先に出ると思います。
そう信じて、ローカル環境はGmailでメールを送っていた時期が僕にもありました。

でもそれはAWSに買収される前の話であって、AWSのメールサービスであるSESが使えないわけないだろ、と最近の私は思い直し、
改めて調査してみたところ、SESでもメールが送れました。

実装

PHPMailerを使うことで、SESを使ってsmtpプロトコルでメールが送れます。

_lib/MailSender.class.php
<?php
namespace util;

// PHPMailerライブラリが存在する場所を指定
// composerで呼び出す場合
require_once __DIR__ . '/../vendor/autoload.php';

// スタンドアロンで呼び出す場合
//require_once __DIR__ . '/../third_party/PHPMailer/src/PHPMailer.php';
//require_once __DIR__ . '/../third_party/PHPMailer/src/SMTP.php';
//require_once __DIR__ . '/../third_party/PHPMailer/src/Exception.php';

require_once __DIR__ . '/MailSender.config.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * PHPMailerを用いてSMTPでメール送信を行う
 * Cloud9やEC2でメールを送るために使用する
 */
class MailSender
{
    private $mailer = null;

    /**
     * 初回実行処理
     *
     * @param string $host SMTPサーバーのホストアドレス
     * @param string $userName SMTPサーバーのユーザー名
     * @param string $password SMTPサーバーのパスワード
     * @return void
     */
    public function __construct(string $host, string $userName, string $password)
    {
        $isShowExceptions = true;
        $mail = new PHPMailer($isShowExceptions);
        $mail->Debugoutput = function($str, $level) { syslog(LOG_ERR, "PHP Mailer:" . $str); };
        $mail->SMTPDebug = 3;
        $mail->CharSet = 'utf-8';

        $mail->isSMTP();
        $mail->Host = $host;
        $mail->Port = 587; // SES は ポート587 を使う
        $mail->Username = $userName;
        $mail->Password = $password;
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'tls'; // SES は tls プロトコルを使う

        $this->mailer = $mail;
    }

    /**
     * メール送信
     *
     * @param string $toAddr 宛先のメアド
     * @param string $fromAddr 差出人のメアド SESに登録されているドメインでしか送れない
     * @param string $fromName 差出人の名前
     * @param string $subject メールのタイトル
     * @param string $body メールの本文 HTMLタグは禁止
     * @return boolean $isSent メール送信の成功可否
     * @throws Exception 例外 メール送信時にエラーが発生した場合。
     */
    public function send(string $toAddr, string $fromAddr, string $fromName, string $subject, string $body): bool
    {
        $this->mailer->setFrom($fromAddr, $fromName);
        $this->mailer->addAddress($toAddr);

        $this->mailer->Subject = $subject;
        $this->mailer->isHTML(false);
        $this->mailer->Body = $body;

        // 送信実行
        try {
            $isSent = $this->mailer->send(); // boolean
        }
        catch (\Exception $e) {
            throw $e;
        }

        return $isSent;
    }
}
_lib/MailSender.config.php
<?php
define('AWS_MAIL_HOST', 'email-smtp.ap-northeast-1.amazonaws.com');
define('AWS_MAIL_USERNAME', 'AKI...OF');
define('AWS_MAIL_PASSWORD', 'BPF...H5');
index.php
<?php
ini_set('display_errors', "On");

require_once __DIR__ . '/_lib/MailSender.class.php';

use util\MailSender;

function test_send()
{
    $params = [
        'host' => AWS_MAIL_HOST,
        'username' => AWS_MAIL_USERNAME,
        'password' => AWS_MAIL_PASSWORD,
        'toAddr' => "me@example.com",
        'fromAddr' => "noreply@example.com",
        'fromName' => "システム管理者",
        'subject' => "送信テスト(タイトル)",
        'body' => "送信テスト(本文)"
    ];

    $mail = new MailSender($params['host'], $params['port'], $params['username'], $params['password']);

    // 送信実行
    $isSent = false;
    try {
        $isSent = $mail->send($params['toAddr'], $params['fromAddr'], $params['fromName'], $params['subject'], $params['body']);
        return $isSent;
    }
    catch (\Exception $e) {
        throw $e->getMessage();
    }
}

$isSent = test_send();

echo $isSent ? "Completed." : "Failed.";
exit;

参考: CodeIgniter3を使っている場合

CodeIgniter3を使っている場合、以下の方法でSESを用いてメールが送れます

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0