19
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SendGrid+PHPでメールを配信したい

Posted at

SendGridはメール配信のウェブサービス。自前でメールサーバを運用するのと比べて、SendGridはスパムメールになりにくいメール配信ができるのが特徴。SMTPだけでなくRESTful APIなどでも送信が可能。無料アカウントでも1日200通まで送信できる。

ここではPHPを使ってSendGridからメールを配信する方法を解説する。PHPからは次のような数行のコードでメール送信ができる。

$sendgrid = new SendGrid('username', 'password');
$email    = new SendGrid\Email();
$email->addTo('foo@bar.com')->
       setFrom('me@bar.com')->
       setSubject('Subject goes here')->
       setText('Hello World!')->
       setHtml('<strong>Hello World!</strong>');
$sendgrid->send($email);

インストール

SendGridのPHPクライアントをComposerでインストールする。

composer.json
{  
  "require": {
    "sendgrid/sendgrid": "2.1.1"
  }
}
$ composer install

メールを送信する

sendgrid-test.php
$sendgrid = new SendGrid($username, $password);
$email    = new SendGrid\Email();
$email->addTo('suin@suin.asia')->
    setFrom('admin@suin.asia')->
    setFromName('サイト管理者')->
    setSubject('パスワード再設定')->
    addCategory('Password reset')->
    setText("パスワード再設定はこちらのリンクをクリックしてください。\nhttp://suin.asia/reset_password?token=123456")->
    setHtml('パスワード再設定はこちらの<a href="http://suin.asia/reset_password?token=123456">リンク<a/>をクリックしてください。');
$result = $sendgrid->send($email);
var_dump($result);

$username$passwordはSendGridに登録したときのものを使う。

このコードを実行すると、こんな形でメールが届く。

Screenshot_2014_09_29_14_36.png

メール送信のエラーハンドリング

$resultmessagesuccessであれば送信成功。errorであれば送信失敗。この仕様を使ってエラーハンドリングが可能。エラーの時は、errorsというキーにエラーの原因が配列で入っている。

成功時

object(stdClass)#6 (1) { ["message"]=> string(7) "success" }

失敗時

object(stdClass)#84 (2) { ["message"]=> string(5) "error" ["errors"]=> array(1) { [0]=> string(23) "Bad username / password" } }

本文にフッターを付けたい

SendGridにはAppsというモジュールみたいな仕組みがあり、これを使うとメールにフッターを追加したり、Gravatarを表示ししたり、開封したかをトラッキングできたりできる。

SendGridにはメールに自動的にフッターをつけるには、Footerアプリを有効にする。SendGrid管理画面のAppsに行って、「Show Disabled Apps」の中から「Footer」を選んで「Enable」する。

We_Make_Email_Delivery_Easy___SendGrid.png

次に、「Show Enablied Apps」に行き、「Footer」の「Setting」でフッターに表示したい文言を書いて保存する。

そうしたら、先ほどのsendgrid-test.phpを実行すると、次のメールのように自動的にフッターが入るようになる。

Screenshot_2014_09_29_14_47.png

開封状況をトラックしたい

これもAppsで「Open Tracking」アプリを有効にする。

ダッシュボード

ダッシュボードを開くと、送信数や開封率などメールの送信状況をひと目で確認できる。

Stats_Dashboard.png

PHP側でカテゴリを設定しておくと、カテゴリごとの送信状況の統計も取ることができる。

    addCategory('Password reset')->
19
18
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
19
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?