Ruby on Rails的Sendgrid API

Mic*_*Lee 11 email ruby-on-rails devise sendgrid mailgun

我似乎无法找到关于如何将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 Key创建一个新客户端",我可以通过两种方式完成:

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
Run Code Online (Sandbox Code Playgroud)

具体在我的应用程序中,我应该把这段代码?我应该把它放在我的邮件程序,我的应用程序邮件程序或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示例(可能会使用sendgrid信息替换mailgun特定信息):

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
Run Code Online (Sandbox Code Playgroud)

此外,如何使用我的邮件程序方法发送邮件程序视图而不是启动学校示例中概述的简单文本?例如,我想发送邮件视图(类似于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方法)?

很抱歉这个问题很长,但希望其他人觉得有用.

谢谢!

NoN*_*nse 7

我会创建一个邮件程序类来做到这一点

class SendgridWebMailer < ActionMailer::Base
  include Sendgrid

  def initialize
    @client = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']).client
  end

  def send_some_email(record, token)
    mail = Mail.new
    // do your mail setup here
    mail = Mail.new
    mail.from = Email.new(email: YOUR_EMAIL_HERE)
    mail.subject = YOUR_SUBJECT

    // I personally use sendgrid templates, but if you would like to use html - 
    content = Content.new(
      type: 'text/html',
      value: ApplicationController.render(
        template: PATH_TO_TEMPLATE,
        layout: nil,
        assigns: IF_NEEDED || {}
      )
    mail.contents = content 

    personalization = Personalization.new
    personalization.to = Email.new(email: EMAIL, name: NAME)
    personalization.subject = SUBJECT

    mail.personalizations = personalization
    @client.mail._('send').post(request_body: mail.to_json)
  end
end
Run Code Online (Sandbox Code Playgroud)

调用它使用

SendgridWebMailer.send_some_email(record, token).deliver_later
Run Code Online (Sandbox Code Playgroud)

为设计

 class MyDeviseMailer < Devise::Mailer
   helper :application # gives access to all helpers defined within `application_helper`.
   include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`

   def reset_password_instructions(record, token, opts={})

      SendgridWebMailer.send_some_email(record, token).deliver_later
   end
end
Run Code Online (Sandbox Code Playgroud)

在 config/devise.rb

# Configure the class responsible to send e-mails.
  config.mailer = 'MyDeviseMailer'
Run Code Online (Sandbox Code Playgroud)

  • 为什么`SendgridWebMailer` 需要从`ActionMailer::Base` 继承? (2认同)

小智 -4

这是一个分步指南,可帮助您将 SendGrid 集成到 RoR 的应用程序中。希望能帮助到你!

\n\n
    \n
  • 首先创建一个 SendGrid 帐户:http: //sendgrid.com/
  • \n
  • 创建一个新的rails文件夹(sendgrid_confirmation)

    \n\n
      \n
    • Rails 新的 sendgrid_confirmation
    • \n
  • \n
  • 导航到 \xe2\x80\x98sendgrid_confirmation\xe2\x80\x99 文件夹

    \n\n
      \n
    • cd sendgrid_confirmation
    • \n
  • \n
  • 在文本编辑器中打开 \xe2\x80\x98sendgrid_confirmation\xe2\x80\x99 (Sublime)

  • \n
  • 创建用户模型(用户是测试模型,您可以根据您的项目\xe2\x80\x99s使用创建任何其他模型)

    \n\n
      \n
    • Rails 生成脚手架 用户名 电子邮件登录
    • \n
    • 耙数据库:迁移
    • \n
  • \n
  • 在 Gemfile 中包含 sendgrid-rails gem

    \n\n
      \n
    • gem \'sendgrid-rails\', \'~> 2.0\'
    • \n
  • \n
  • 在终端中运行捆绑安装

    \n\n
      \n
    • 捆绑安装
    • \n
  • \n
  • 使用secrets.yml定义SendGrid API凭据:(config/secrets.yml)\n生产:\n sendgrid_username:your-sendgrid-username\n sendgrid_password:your-sendgrid-password\n(开发和测试中不会发送电子邮件环境。因此您只能为生产定义它。)

  • \n
  • 生成 Mailer 类。邮件程序类充当电子邮件视图的控制器。

    \n\n
      \n
    • Rails 生成邮件程序 UserNotifier
    • \n
  • \n
  • 打开 app/mailers/user_notifier.rb 并添加以下向用户发送注册邮件的邮件程序操作

  • \n
\n\n

\n\n

class UserNotifier < ActionMailer::Base\n  default :from => \'any_from_address@example.com\'\n  # send a signup email to the user, pass in the user object that  contains the user\'s email address\n  def send_signup_email(user)\n    @user = user\n    mail(:to => @user.email,\n      :subject => \'Thanks for signing up for our amazing app\')\n  end\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n
    \n
  • 创建一个文件 app/views/User_notifier/send_signup_email.html.erb 如下:(这将创建一个与我们的操作相对应的视图并为我们的电子邮件输出 HTML)
  • \n
\n\n

\n\n

<!DOCTYPE html>\n    <html>\n        <head>\n                <meta content=\'text/html; charset=UTF-8\' http-equiv=\'Content-Type\' />\n        </head>\n        <body>\n                <h1>Thanks for signing up, <%= @user.name %>!</h1>\n                <p>Thanks for joining and have a great day! Now sign in and do awesome things!</p>\n        </body>\n    </html>\n
Run Code Online (Sandbox Code Playgroud)\n\n
    \n
  • 转到用户控制器 (app/controllers/users_controller.rb) 并在保存用户时添加对 UserNotifier.send_signup_email 的调用。
  • \n
\n\n

\n\n

def create\n  @user = User.new(user_params)\n  respond_to do |format|\n    if @user.save\n      UserNotifier.send_signup_email(@user).deliver\n      format.html { redirect_to @user, notice: \'User was successfully created.\' }\n      format.json { render :show, status: :created, location: @user }\n    else\n      format.html { render :new }\n      format.json { render json: @user.errors, status: :unprocessable_entity }\n    end\n  end\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n
    \n
  • 更新您的 config/environment.rb 以将 ActionMailer 设置指向 SendGrid\xe2\x80\x99s 服务器。您的environment.rb 文件应如下所示:
  • \n
\n\n

\n\n

# Load the Rails application.\nrequire File.expand_path(\'../application\', __FILE__)\n\n# Initialize the Rails application.\nRails.application.initialize!\n\nActionMailer::Base.smtp_settings = {\n    :user_name => \xe2\x80\x98your_sendgrid_username\xe2\x80\x99,\n    :password => \'your_sendgrid_password\xe2\x80\x99,\n    :domain => \xe2\x80\x98your_domain.com\',\n    :address => \'smtp.sendgrid.net\',\n    :port => 587,\n    :authentication => :plain,\n    :enable_starttls_auto => true\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
    \n
  • 指向您的 config/routes.rb 文件以在加载时加载索引页面。在routes.rb 文件中添加以下内容:
  • \n
\n\n

\n\n

get \xe2\x80\x98/\xe2\x80\x99 => \xe2\x80\x98users#index\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n\n

就是这样!现在,当您创建新用户时,您应该会收到一封来自 的电子邮件(在您提供的 user.email 上)any_from_address@example.com。您可以将其更改为:来自 的电子邮件app/mailers/user_notifier.rb。更改默认的 :from 地址,它应该可以做到这一点。您可以在同一文件内的 send_signup_mail 方法中添加电子邮件参数,并添加您\xe2\x80\x99d 想要添加的详细信息。您还可以更改消息正文app/views/user_notifier/send_signup_email.html.erb以显示您想要的任何内容。

\n

  • 失望!这不是一个答案,而是从过时的做法中剪切和粘贴的,这种做法可以很容易地在许多其他地方找到。 (6认同)
  • 尽管此答案正确解释了(如 sendgrid 文档)如何使用 SMTP 从 RoR 应用程序发送电子邮件,但它没有回答所提出的问题。该问题明确询问如何使用 sendgrid API 而不是 SMTP。 (4认同)