如何将Rails ApplicationMailer配置为使用API​​或RestClient代替smtp

问题描述

是否可以将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等)时,它的处理速度较慢,更容易出错,并且肯定需要进行更多工作来手动处理模板渲染等。

解决方法

如果您为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',...}

希望您能走上正确的轨道!如果您发现自己创造了一些有用的东西,也许您可​​以将其做成宝石并与社区分享:)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...