LoginSignup
21
28

More than 5 years have passed since last update.

Heroku + PHP + SendGrid でメールを送信する

Posted at

Heroku 環境で、SendGrid アドオンを使って、PHP からメールを送信します。

SendGrid アドオンを追加

メール送信には、SendGrid アドオンを利用します。(無料プランあり: 200通/日制限)

https://addons.heroku.com/sendgrid

$ heroku addons:add sendgrid

Sendgrid-php を追加

PHP から SendGrid を利用するライブラリとして、Sendgrid-php を利用します。

https://github.com/sendgrid/sendgrid-php

composer.jsonrequireに、以下を追加します。

    "require": {
      "sendgrid/sendgrid": "2.0.5"
    }

composer install or composer updateすると、Sendgrid-php が利用できます。

PHPからメール送信

Sendgrid-php を利用して、PHP コードからメールを送信します。

まず、autoloader を読み込みます。

次に SendGrid の認証情報をSendGridクラスのコンストラクタで指定します。認証情報は、以下の環境変数でセットされるので、これをgetenv()で取得してセットしています。

  • SENDGRID_USERNAME = 接続ユーザ名
  • SENDGRID_PASSWORD = 接続パスワード

あとは、送信するメールの情報を各メソッドで指定して、最後にsend()メソッドで送信するだけです。もちろん日本語も OK です。

<?php
require __DIR__ . '/../vendor/autoload.php'; // path to vendor/

$sendgrid = new SendGrid(getenv('SENDGRID_USERNAME'), getenv('SENDGRID_PASSWORD'));
$email = new SendGrid\Email();
$email->addTo('to@exmaple.com')->
    setFrom('from@example.com')->
    setSubject('件名')->
    setText('こんにちは!');

$sendgrid->send($email);

21
28
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
21
28