在 Rails 应用上使用 SendGrid 发送交易电子邮件

Send transactional email with SendGrid on a Rails app

我正尝试在客户预订 Rails 应用程序时使用 Sendgrid 发送交易电子邮件。

我确实按要求创建了一个动态模板。 当我使用正确的正文和我的 Sendgrid API 密钥向 POST 发出 https://api.sendgrid.com/v3/mail/send 的 POST 请求时,它有效,我确实收到了确认电子邮件。

但是,我是一个 Rails 新手,我真的不知道如何处理文档中提供的这段代码:

require 'sendgrid-ruby'
include SendGrid

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'], impersonate_subuser: The subuser's username. This header generates the API call as if the subuser account was making the call.)
data = JSON.parse('{
  "name": "example_name",
  "generation": "dynamic"
}')

response = sg.client.templates.post(request_body: data)
puts response.status_code
puts response.headers
puts response.body

在此先感谢您的帮助!

此处为 Twilio SendGrid 开发人员布道师。

查看 the documentation here that shows all the options you can use to send an email with the Ruby library(请原谅使用 include)。

根据文档,这里有一个应该能满足您需求的简短片段:

require 'sendgrid-ruby'

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
mail = SendGrid::Mail.new

mail.from = SendGrid::Email.new(email: "YOUR_FROM_ADDRESS")
mail.subject = "Your fancy, exciting subject line"
mail.template_id = "YOUR_TEMPLATE_ID"

personalization = SendGrid::Personalization.new
personalization.add_to(SendGridEmail.new(email: 'YOUR_CUSTOMER_EMAIL'))
personalization.add_dynamic_template_data({
  "name" => "example_name",
  "generation" => "dynamic"
})
mail.add_personalization(personalization)

sg.client.mail._("send").post(request_body: mail.to_json)

看看this specific example in the SendGrid Ruby library docs too