メールの本文自体を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
というオブジェクトは、本文に含まれるなんらかのキーを送信時にリプレースするためのもの。ちなみに、from
とpersonalizations
のなかのto
は必須らしい。
追記
substitutions
は基本的にキー・バリューのフォーマットをとるが、ひとつでも文字列ではない数値などが渡ると、エラーの内容が全部NULLの400 Bad Requestを返してくる。詳しくはDocsのエラーの項目を参照するとよい。
https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html