【问题标题】:Send transactional email with SendGrid on a Rails app在 Rails 应用程序上使用 SendGrid 发送事务性电子邮件
【发布时间】:2022-02-05 16:08:23
【问题描述】:

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

我确实根据需要创建了一个动态模板。 当我使用正确的正文和我的 Sendgrid API 密钥通过 POSTMAN 向 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

提前感谢您的帮助!

【问题讨论】:

  • 1.你不需要include Sendgrid。永远不要在全局级别上使用include(不在类或模块内。2. 只需将这些东西放入控制器中的操作并点击路由?:)
  • 感谢您的回复,玛丽安。 1 - 适当注意! 2 - 我不明白我可以把“从”、“到”、动态模板 ID 放在哪里。你知道吗?非常感谢!

标签: ruby-on-rails ruby sendgrid sendgrid-templates


【解决方案1】:

这里是 Twilio SendGrid 开发人员宣传员。

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

根据文档,这里有一个可以满足您需求的快速 sn-p:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2014-10-01
    相关资源
    最近更新 更多