如何将 Rails ApplicationMailer 配置为使用 API(或 RestClient)而不是 smtp

jpw*_*ynn 1 api ruby-on-rails actionmailer

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
  }

Run Code Online (Sandbox Code Playgroud)

也许有类似的东西

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

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

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

Mar*_* G. 5

我认为如果您为 ActionMailer 创建自定义的 Delivery_method 就可以做到这一点。

为此,您需要:

  1. 编写一个响应几个方法的新类
  2. 注册您的delivery_method
  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', ...}
Run Code Online (Sandbox Code Playgroud)

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