14
18

More than 5 years have passed since last update.

Laravel + SendGrid Web API でメール送信する

Posted at

環境

  • PHP 7.2
  • Laravel 5.5
  • SendGrid Web API V3

まえがき

Laravel でメール送信する方法はいくつかあるが、今回は SendGrid を使用する。
会員登録が必要だが、12,000 通/月 までは無料。

SendGrid には SMTP を使用する方法と、API を使用する方法がある。
今回は API を使用する。
両方試したが、圧倒的に API の方が使いやすい。

手順

API キーを作成する

公式サイトの手順に従って作成し、API キーをメモしておく。

メールが送信できるかテストする

curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header 'Authorization: Bearer ここにAPI Keyを入れる' \
  --header 'Content-Type: application/json' \
  --data '{"personalizations": [{"to": [{"email": "test-to@gmail.com"}]}],"from": {"email": "test-from@gmail.com"},"subject": "Hello, World!","content": [{"type": "text/plain", "value": "Heya!"}]}'

SendGrid のライブラリをインストール

composer.json
"require": {
    "sendgrid/sendgrid": "~6.2"
},

ライブラリを使用してメールを送信する

app/Http/Controllers/MailController.php
use SendGrid\Content;
use SendGrid\Email;
use SendGrid\Mail;

...

$from     = new Email('From名', 'Fromアドレス');
$to       = new Email('To名', 'Toアドレス');
$subject  = 'テストタイトル';
$content  = new Content(
    'text/plain',
    'テスト本文'
);
$mail     = new Mail($from, $subject, $to, $content);
$sendGrid = new \SendGrid('APIキー');
$response = $sendGrid->client->mail()->send()->post($mail);

これで届いていれば OK!

メール本文に Blade テンプレートを使う場合

以下のように文字列に変換すればそのまま使える。
もちろん値も渡せる。

app/Http/Controllers/MailController.php
...

$sendData = [
    'id' => $request->get('id'),
];

$content = new Content(
    'text/plain',
    strval(
        view(
            'emails/templates/test_mail',
            $sendData
        )
    )
);
14
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
14
18