LoginSignup
4
6

More than 3 years have passed since last update.

heroku + PHP + SendGrid環境でメール送信するのに詰まったメモ

Posted at

はじめに

自作サイトをherokuにアップしたものの、PHPのmb_send_mail()が動かなかった。
調べてみたところ、そもそもherokuのデフォルト設定ではメール送信には対応してないとのこと。

https://qiita.com/negi3d/items/2714534897f90915d392
上記記事を参考に、SendGridアドオンの導入→APIキーの取得云々を済ませコードを追加しても、動かず手詰まりに。
heroku logs --tail
でlogを見てみると、
SendGrid\Emailなんてものはないですよ、と怒られている模様。

解決策

SendGridの公式サポートサイトを確認した。
https://sendgrid.kke.co.jp/docs/Integrate/Code_Examples/v3_Mail/php.html
現在はSendGrid\EmailではなくSendGrid\Mailを利用するのが正しいようだ。

send.php
<?php
      require 'vendor/autoload.php';

      $email = new \SendGrid\Mail\Mail();
      $email->setFrom("test@example.com", "Example User");
      $email->setSubject("Hello from SendGrid");
      $email->addTo("test@example.com", "Example User");
      $email->addContent("text/plain", "Hello world");
      $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
      try {
          $response = $sendgrid->send($email);
          print $response->statusCode() . "\n";
          print_r($response->headers());
          print $response->body() . "\n";
      } catch (Exception $e) {
          echo 'Caught exception: '. $e->getMessage() ."\n";
      }
?>
4
6
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
4
6