【发布时间】:2016-07-24 16:36:40
【问题描述】:
我似乎找不到关于如何将 Sendgrid Web API 集成到 Ruby on Rails 应用程序的分步教程。我对此很陌生,所以也许我遗漏了一些明显的东西。
我想使用 Sendgrid Web API 而不是 smtp 传递方法(mailgun 在这里讨论了 Web API 相对于 SMTP 方法的好处:https://documentation.mailgun.com/quickstart-sending.html,我认为 Sendgrid 要么具有相同的好处或者我以后可能会切换到mailgun)。
安装 sendgrid gem (https://github.com/sendgrid/sendgrid-ruby) 后,文档告诉我“使用您的 SendGrid API 密钥创建一个新客户端”,我可以通过两种方式完成:
require 'sendgrid-ruby'
# As a hash
client = SendGrid::Client.new(api_key: 'YOUR_SENDGRID_APIKEY')
# Or as a block
client = SendGrid::Client.new do |c|
c.api_key = 'YOUR_SENDGRID_APIKEY'
end
我应该把这段代码放在我的应用程序的什么地方?我应该把它放在我的邮件程序、我的应用程序邮件程序还是 config/environments/production.rb 文件中?
我查看了本教程,其中介绍了如何设置 Mailgun API:https://launchschool.com/blog/handling-emails-in-rails
根据本教程,client = SendGrid::Client.new(api_key: 'YOUR_SENDGRID_APIKEY') 行实际上应该进入邮件方法本身。请参阅下面的 launchschool.com 示例(可能将 mailgun 特定信息替换为 sendgrid 信息):
class ExampleMailer < ActionMailer::Base
def sample_email(user)
@user = user
mg_client = Mailgun::Client.new ENV['api_key']
message_params = {:from => ENV['gmail_username'],
:to => @user.email,
:subject => 'Sample Mail using Mailgun API',
:text => 'This mail is sent using Mailgun API via mailgun-ruby'}
mg_client.send_message ENV['domain'], message_params
end
end
此外,我如何让我的邮件方法发送邮件视图,而不是像 launchschool 示例中所述的简单文本?例如,我想发送一个邮件视图(类似于 account_activation.html.erb),而不是发送文本“此邮件是使用...发送的”。
最后,我在我的应用程序中使用了 Devise,我想让 Devise 使用 Web API 来发送电子邮件(即密码重置等)。这是否意味着我需要为 Devise 创建一个自定义邮件?如果是这样,我该怎么做?
根据 Devise (https://github.com/plataformatec/devise/wiki/How-To:-Use-custom-mailer),我应该“创建一个扩展 Devise::Mailer 的类”。这是否意味着我只需在我的邮件文件夹中创建一个文件,其中包含文档中列出的信息?我是否需要单独的 Devise 邮件程序,或者我可以从 Devise 邮件程序继承现有的邮件程序?最后,我如何告诉 devise 使用 sendgrid web api 发送电子邮件(而不是简单的 smtp 方法)?
抱歉这个问题太长了,但希望其他人觉得它有用。
谢谢!
【问题讨论】:
-
没试过,但看起来很有希望:github.com/eddiezane/sendgrid-actionmailer
标签: ruby-on-rails email devise sendgrid mailgun