【问题标题】:How can Rails ApplicationMailer be configured to use an API (or RestClient) instead of smtp如何将 Rails ApplicationMailer 配置为使用 API(或 RestClient)而不是 smtp
【发布时间】:2020-10-19 23:07:32
【问题描述】:

是否可以将 Rails 的 ApplicationMailer(以前的 ActionMailer)配置为使用 REST API 而不是 SMTP?

换句话说,替换

  self.smtp_settings = {
    :address => ENV['MAILER_URL'],
    :port => ENV['MAILER_PORT'],
    :domain => ENV['MAILER_DOMAIN'],
    :authentication => :login,
    :user_name => ENV['MAILER_USER'],
    :password => ENV['MAILER_PWD'],
    :enable_starttls_auto => true
  }

也许有类似的东西

config.action_mailer.delivery_method = :rest_client  # JUST A MADE UP EXAMPLE

config.action_mailer.rest_client = {
  api_auth_header:{"Authorization" => "Bearer #{ENV['MY_REST_MAILER_API_KEY']}" ,
  api_endpoint: ENV['MY_REST_MAILER_API_URL']
}

我看到 Sendgrid 和其他 ESP 提供 gem 的特定 gem,但我正在寻找通用 ActionMailer-to-Rest 解决方案,我可以在其中指定任意 api 端点等,而不是绑定到 gem (或提供 gem 的提供商)并且仍然拥有 ActionMailer 提供的模板等功能。

完全跳过 ActionMailer 类并只编写一个使用 RestClient 的新邮件程序类并非不可能,事实上我们已经针对某些特殊情况这样做了。但是对于普通电子邮件,每次您只想创建一个新的电子邮件类型(customer_thank_you.html.haml、customer_welcome.html.haml 等)时,它的速度较慢、更容易出错,而且手动处理模板渲染等的工作肯定会更多。 .

【问题讨论】:

    标签: ruby-on-rails api actionmailer


    【解决方案1】:

    如果你为 ActionMailer 创建一个自定义的 delivery_method,我认为你可以做到这一点。

    为此,您需要:

    1. 编写一个响应几个方法的新类
    2. 注册您的交付方式
    3. 配置 action_mailer 以在您的配置中使用它

    它在实践中的样子可能是这样的:

    # lib/rest_mail.rb
    # ActionMailer will instantiate this class to send the email.
    class RestMail
    
      # initialize is called with the settings provided from your config
      def initialize(settings)
        @settings = settings
      end
    
      # deliver! is the only other required method.  It is passed the mail object to send.
      # mail.encoded returns the email in the format needed to send it.  
      # Look at other mail delivery methods for inspiration (Mail::Sendmail, Mail::FileDelivery, Mail::SMTP, etc)
      def deliver!(mail)
        @client.post(url: @settings['url'], payload: mail.encoded)
      end
    
      def rest_client
        @client ||= MyRestClient.new(@settings)
      end
    end
    
    # config/initializers/custom_mailer_delivery_methods.rb
    ActionMailer::Base.add_delivery_method :rest_mail, RestMail
    
    # optionally, specify defaults with the optional hash as the last parameter:
    ActionMailer::Base.add_delivery_method :rest_mail, RestMail, {url: 'http://mydefaulturl.com'}
    
    # config/environments/application.rb
    config.action_mailer.delivery_method = :rest_mail
    config.action_mailer.rest_mail_settings = { url: 'https://example.com', ...}
    

    希望这能让您走上正轨!如果你发现你创造了一些有用的东西,也许你可以把它制作成宝石并与社区分享:)

    【讨论】:

    • 这是一个非常酷的答案,谢谢。如果我有什么工作会发回这里。
    • @jpw 对你有用吗?
    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多