FuelPHPでSendgridを使ってメール送信したいときのメモ。
手順1
composer.jsonを修正します。
1 2 3 4 5 6 7 |
"require": { "php": ">=5.3.3", ・ ・ "sendgrid/sendgrid": "~6.0", ・ }, |
手順2
composer.pharを使ってインストールする。
1 2 |
$ php composer.phar self-update $ php composer.phar update |
手順3
共通メソッドを用意する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
/** * sendgrid を使ってメールを配信する * * @param array $to_address * @param unknown $subject * @param unknown $body * @throws \InvalidArgumentException */ public static function mail_sendgrid(array $to_address, $subject, $body) { Log::debug('mail_send : ' .print_r($to_address,true)); if (empty($to_address)) { throw new \InvalidArgumentException('to_addressは必須です。'); } if (empty($subject)) { throw new \InvalidArgumentException('subjctは必須です。'); } if (empty($body)) { throw new \InvalidArgumentException('bodyは必須です。'); } try { // 重複アドレスは削除 $to_address = array_unique($to_address); $from = new SendGrid\Email("xxxxx", "xxxx@example.com"); $to = new SendGrid\Email($to_address[0], $to_address[0]); $content = new SendGrid\Content("text/plain", $body->render()); $mail = new SendGrid\Mail($from, $subject, $to, $content); // 複数宛先があった場合 foreach ($to_address as $k => $toadd) { if ($k == 0) { continue; } $email2 = new SendGrid\Email($toadd, $toadd); $mail->personalization[0]->addTo($email2); } $apiKey = 'Sendgridで取得したAPIキー'; $sg = new \SendGrid($apiKey); $response = $sg->client->mail()->send()->post($mail); Log::debug(print_r($response, true), '$response'); } catch(\SendGrid\Exception $e) { Log::warning('メール送信に失敗しました。 '.print_r($e, true)); } } |
メールテンプレートを使ってメール送信する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$to_address_arr[] = 'test@example.com'; // メールを送信するためのテンプレートを定義 $body = \Theme::instance()->view('mail-template/sample', array( 'send_username' => '本文に埋め込む名前', 'send_email' => '本文に埋め込むメールアドレス', 'send_tel_no' => 本文に埋め込む'電話番号', 'subject' => '本文に埋め込む件名', 'note' => '本文に埋め込む埋め込み文字' ) ); // メールを送信する \Util::mail_sendgrid($to_address_arr, 'メールの件名', $body, null); |
参考サイト
https://sendgrid.kke.co.jp/blog/?p=1066
https://sendgrid.kke.co.jp/docs/Integrate/Code_Examples/v2_Mail/php.html
https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php