提问者:小点点

Sendgrid API for Ruby on Rails


我似乎找不到有关如何将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 密钥创建一个新客户端”,我可以通过 2 种方式执行此操作:

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/environment/production.rb 文件中?

我看了一下本教程,介绍了如何设置 Mailgun API: https://launchschool.com/blog/handling-emails-in-rails

根据本教程,看起来行客户端 = SendGrid::Client.new(api_key:“YOUR_SENDGRID_APIKEY”)实际上应该进入邮件方法本身。有关 launchschool.com 示例,请参见下文(大概是将邮件枪特定信息替换为发送网格信息):

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

此外,如何让我的邮件程序方法来发送邮件程序视图,而不是启动学校示例中概述的简单文本?例如,不要发送文本“此邮件是使用...发送的”。我想发送一个邮件视图(类似于account_activation.html.erb)。

最后,我在我的应用程序中使用Devise,我想让Devise使用Web API发送电子邮件(即密码重置等)。这是否意味着我需要为 Devise 创建自定义邮件程序?如果是这样,我该怎么做?

根据 Devise (https://github.com/plataformatec/devise/wiki/How-To:-Use-custom-mailer),我应该“创建一个扩展 Devise::Mailer 的类”。这是否意味着我只是在我的邮件文件夹中制作一个文件,其中包含文档中列出的信息?我是否需要一个单独的邮件程序来管理Devise,或者我可以从Idese邮件程序继承现有的邮件程序吗?最后,我如何告诉设计使用sendgrid web api发送电子邮件(而不是简单的smtp方法)?

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

谢谢!


共3个答案

匿名用户

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

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

使用 调用它

SendgridWebMailer.send_some_email(record, token).deliver_later

对于设计

 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

in config/devise.rb

# Configure the class responsible to send e-mails.
  config.mailer = 'MyDeviseMailer'

匿名用户

编辑:

不幸的是,此方法仅适用于远程图像。

好的,这就是我是如何做到的。可能有更好的方法可以做到这一点,但这对我有用。

因此,在发送电子邮件时,您最初将通过执行类似UserMailer.reset_email(user).deliver之类的操作来发送它。因此,删除交付并将其保存到变量中:

对象 = UserMailer.reset_email(用户)

深深嵌套在此的是电子邮件的正文。它所在的位置可能会随着上下文而变化,所以我的建议是将对象返回到前端,以便您可以深入研究并找到它。对我来说,尸体就住在这里:

object = UserMailer.reset_email(user)
body = object.body.parts.last.body.raw_source

好的,现在你得到了原始来源。现在要发送它,这是我创建的方法:

def self.sendEmail(from,to,subject,message)
    from = Email.new(email: from)
    to = Email.new(email: to)
    content = Content.new(type: 'text/html', value: message)
    mail = Mail.new(from, subject, to, content)

    sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
    response = sg.client.mail._('send').post(request_body: mail.to_json) 
    puts response.status_code
    puts response.body
    puts response.headers
  end

这样称呼它(在我的例子中,它在用户模型中):

User.sendEmail('noreply@waydope.com',user.email,'Reset Password', body)

确保将内容类型从纯更改为 html,否则您将只获得原始代码。希望这有帮助。

匿名用户

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

>

  • 首先在以下位置创建一个 SendGrid 帐户:http://sendgrid.com/
  • 创建新的 rails 文件夹 (sendgrid_confirmation)

    • 轨道新sendgrid_confirmation

    导航到“sendgrid_confirmation”文件夹

    • 光盘sendgrid_confirmation

    在文本编辑器中打开“sendgrid_confirmation”(Sublime)

    创建用户模型(用户是测试模型,您可以根据项目的使用情况创建任何其他模型)

    • 轨道生成脚手架用户名电子邮件登录
    • 耙子数据库:迁移

    在 Gemfile 中包含 sendgrid-rails gem

    • 宝石 '森格栅栏', '~

    在终端中运行捆绑安装

    • 捆绑安装

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

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

    • 轨道生成邮件程序用户通知程序

    打开 app/mailers/user_notifier.rb 并添加以下邮件程序操作,该操作向用户发送注册邮件

    class UserNotifier < ActionMailer::Base
      default :from => 'any_from_address@example.com'
      # send a signup email to the user, pass in the user object that  contains the user's email address
      def send_signup_email(user)
        @user = user
        mail(:to => @user.email,
          :subject => 'Thanks for signing up for our amazing app')
      end
    end
    
    • 创建一个文件 app/views/User_notifier/send_signup_email.html.erb,如下所示:(这将创建一个与我们的操作相对应的视图,并为我们的电子邮件输出 HTML)
    <!DOCTYPE html>
        <html>
            <head>
                    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
            </head>
            <body>
                    <h1>Thanks for signing up, <%= @user.name %>!</h1>
                    <p>Thanks for joining and have a great day! Now sign in and do awesome things!</p>
            </body>
        </html>
    
    • 转到用户控制器(应用/控制器/users_controller.rb),并在保存用户时添加对UserNotifier.send_signup_email的调用。
    def create
      @user = User.new(user_params)
      respond_to do |format|
        if @user.save
          UserNotifier.send_signup_email(@user).deliver
          format.html { redirect_to @user, notice: 'User was successfully created.' }
          format.json { render :show, status: :created, location: @user }
        else
          format.html { render :new }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      end
    end
    
    • 更新您的 config/environment.rb 以将您的 ActionMailer 设置指向 SendGrid 的服务器。您的 environment.rb 文件应如下所示:
    # Load the Rails application.
    require File.expand_path('../application', __FILE__)
    
    # Initialize the Rails application.
    Rails.application.initialize!
    
    ActionMailer::Base.smtp_settings = {
        :user_name => ‘your_sendgrid_username’,
        :password => 'your_sendgrid_password’,
        :domain => ‘your_domain.com',
        :address => 'smtp.sendgrid.net',
        :port => 587,
        :authentication => :plain,
        :enable_starttls_auto => true
    }
    
    • 将 config/routes.rb 文件指向加载时加载索引页。在 routes.rb 文件中添加以下内容:
    get ‘/’ => ‘users#index’
    

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