LoginSignup
0
1

More than 3 years have passed since last update.

SendGrid + CakePHPでWeb API利用時にTemplateを使う

Last updated at Posted at 2019-08-21

SMTPを使うならいつものsetTemplateでテンプレートを指定できますが、Web APIを使う場合SendGridの純正ライブラリはCakePHP用に書かれたものではないためCakePHPのテンプレートを使うようになっていません。
テンプレートに値を埋めたテキスト(HTML)を取得して、addContentします。

宛先や件名の設定などは省略しているので公式を参照してください。

// 実際はComponentにして使っています。以下のコードはControllerで使うことを想定しています

// Viewを自分でnewするので使えるようにしておきます
use Cake\View\View;

$view = new View($this->request, $this->response);

// $varsにはテンプレートで使う値が入ってます
// ['username' => 'テスト太郎']
// のような連想配列を想定しています
// viewに値を渡すとき使う$this->set()と同じなので設定できればどう書いてもいいです
foreach ($vars as $key => $value) {
    $view->set($key, $value);
}

// $templateにテンプレートを指定します
// Template直下から指定する必要があるので、
// いつものEmailテンプレートを使いたければ Email/text(またはhtml)/テンプレート名 にします
// これで$contentにテンプレートに値を埋め込んだテキストが入ります
$content = $view->render($template, false);

// マルチパートにしたければplain、html両方addContentします
if ($format == 'text') {
    $email->addContent('text/plain', $content);
} else {
    $email->addContent('text/html', $content);
}

$sendgrid = new SendGrid('API-KEY');
try {
    $response = $sendgrid->send($email);
    // ログは好きにしてください
    $this->log($response->statusCode());
    $this->log($response->headers());
    $this->log($response->body());
} catch (Exception $e) {
    $this->log('Caught exception: '. $e->getMessage(), LOG_ERR);
}

SendGridの例を書きましたが、Controller中でTemplateに値を埋めた状態のテキスト取得する方法は汎用的なので知っておくと他でも使えます。

0
1
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
0
1