LoginSignup
2
1

More than 5 years have passed since last update.

Ruby上でササッとSendGridのTemplateを使う

Last updated at Posted at 2017-07-29

メールの本文自体をSendGrid上でTemplateとして管理し、送信をアプリケーション側からやる方法。

mailsender.rb
require "sendgrid-ruby"

_options = JSON.parse({
  template_id: "d6e5d510-2619-43ba-bfd6-b6c69b83b8fc",
  personalizations: [
    to: [
      { email: "saruo@example.ne.jp" }
    ],
    substitutions: {
      "[%name%]": "Saruta Saruo"
    }
  ],
  from: {
    email: "ec@company.co.jp"
  }
}.to_json())

sendgrid = SendGrid::API.new(api_key: "** Your API Key **")
sendgrid.client.mail._("send").post(request_body: _options)

substitutionsというオブジェクトは、本文に含まれるなんらかのキーを送信時にリプレースするためのもの。ちなみに、frompersonalizationsのなかのtoは必須らしい。

追記
substitutionsは基本的にキー・バリューのフォーマットをとるが、ひとつでも文字列ではない数値などが渡ると、エラーの内容が全部NULLの400 Bad Requestを返してくる。詳しくはDocsのエラーの項目を参照するとよい。
https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html

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