提问者:小点点

使用 Rails 应用程序上的 SendGrid 发送事务性电子邮件


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

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

但是,我是 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

提前感谢您的帮助!


共1个答案

匿名用户

Twilio SendGrid 开发人员布道者在这里。

查看此处的文档,其中显示了可用于使用 Ruby 库发送电子邮件的所有选项(请原谅使用 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)

在 SendGrid Ruby 库文档中也看看这个具体的例子。