はじめに
以前、上記の記事を書いたのはCI3でSESを使ってメールを送る方法がわからず、調べる時間もなかったためでした。
phpMailerで送れるならCI標準機能でも送れるはずだと思って、改めて調査しなおしました。
実装
以下のようにすれば、CodeIgniter3の標準機能を利用してSESからメールが送れます。
application/config/email.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config = array(
'useragent' => 'CodeIgniter',
'protocol' => 'smtp', // AWS SES の場合は smtp を指定すること
'mailpath' => '/usr/sbin/sendmail', // Sendmail へのパス
'smtp_host' => 'email-smtp.ap-northeast-1.amazonaws.com', // e.g. AWS SES のエンドポイントを指定
'smtp_user' => 'AKI...OF', // e.g. AWS SES のSMTPユーザーアクセスキー
'smtp_pass' => 'BPF...H5', // e.g. AWS SES のSMTPユーザーシークレットキー
'smtp_port' => 587, // e.g. 25, 465(gmail smtp ssl), 587(AWS SES)
'smtp_timeout' => 5, // seconds
'smtp_keepalive' => FALSE, // 持続的SMTP接続の有効化
'smtp_crypto' => 'tls', // e.g. AWS SES 'tls', smtp_hostのプロトコルになる e.g. 'tls://email-smtp.ap-northeast-1.amazonaws.com'
'wordwrap' => FALSE, // ワードラップの有効化設定
'wrapchars' => 76, // 何番目の文字で折り返すか
'mailtype' => 'text', // e.g. 'text', 'html'
'charset' => 'utf-8', // e.g. 'utf-8', 'iso-8859-1'
'validate' => TRUE, // メールアドレスを検証するかどうか
'priority' => 3, // メールの優先度。1~5。 1 = 最高 3 = 通常 5 = 最低
'crlf' => "\r\n", // 必ずダブルクオーテーションにすること。シングルだと送れないしエラーも出ない e.g. "\r\n", "\n", "\r"
'newline' => "\r\n", // 必ずダブルクオーテーションにすること。シングルだと送れないしエラーも出ない e.g. "\r\n", "\n", "\r"
'bcc_batch_mode' => FALSE, // BCC バッチモードを有効にするかどうか
'bcc_batch_size' => 200, // 各 BCC バッチで送るメール件数。
'dsn' => TRUE // サーバーからのメッセージ通知を有効にする
);
application/controllers/Test.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$isSent = $this->_sendMailTest();
echo $isSent ? "メール送った" : "メール送れなかった";
exit;
}
private function _sendMailTest()
{
$this->load->library('email'); // @see config/email.php
$fromAddr = 'noreply@example.com'; // SESに登録済のアドレスでしか送れない。適当なアドレスで送っても届かない
$fromName = 'システム管理者'; // ここは適当な名前で送っても大丈夫
$toAddr = 'me@example.com';
$this->email->from($fromAddr, $fromName);
$this->email->to($toAddr);
$subject = "メールタイトルです";
$message = "メール本文です";
$this->email->subject($subject);
$this->email->message($message);
$isSent = $this->email->send(); // boolean
return $isSent;
}
躓きポイント
- プロトコルは
smtp
を指定すること - ポートは
587
にすること - 暗号化プロトコルは
tls
にすること - 差出人(
from
)のアドレスはSESに登録されたものしか使用できない- 適当なアドレスで送るとメールが届かない
- 改行の囲み文字は必ずダブルクオーテーションにすること
- シングルクオーテーションだとメールが届かないしエラーも出ない