LoginSignup
12
11

More than 5 years have passed since last update.

CakePHP3からAmazon SESを使ってメールを送る

Posted at

SESの設定

SESの初期設定は、すでにQiitaにたくさん情報があるので、そちらを参考に
http://qiita.com/search?utf8=✓&sort=rel&q=SES&sort=rel

「Create My SMTP Credentials」を実行し、SMTP UsernameSMTP Passwordを取得します
さらに、Amazon SESのダッシュボードに記載されているServer Nameも必要です

Fromで使うメールアドレス、Toで使うメールアドレスともに、
「Verified Senders」>「Email Addresses」から「Verify a New Email Address」でVerifyしておきましょう

CakePHP

config/app.phpに、SESの設定を投入します

config/app.php
    'EmailTransport' => [
        'default' => [
            変更なし
        ],
        'ses' => [
            'className' => 'Smtp',
            'host' => '<Server Name>',
            'port' => 587,
            'timeout' => 30,
            'username' => '<SMTP Username>',
            'password' => '<SMTP Password>',
            'tls' => true,
        ]
    ],

実際に送信する処理

$email = new Email('default');
if (!$debug) {
    $email->transport('ses');
    $email->returnPath($from);
} else {
    $email->transport()->config(['additionalParameters' => '-f ' . $from]);
}
$isCli = php_sapi_name() === 'cli';
if ($isCli) {
    // CLIからの送信の場合はdomainメソッドを呼ぶ
    // http://book.cakephp.org/3.0/en/core-libraries/email.html#sending-emails-from-cli
    preg_match('/@(.*)$/', $from, $matches);
    $domain = $matches[1];
    $email->domain($domain);
}
$email->from($from);
$email->subject($subject);
$email->to($to);
$email->send($body);

こんな感じで送信します
メールが届くことが確認できたら、プロダクションアクセスを申請しましょう

注意点

SESのプロダクションアクセスを手に入れるまでは、送信元のメールアドレスはもちろん、送信先のメールアドレスも承認されたものでないとなりません
忘れずにVerifyしておきましょう

12
11
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
12
11