2011-07-04 29 views
10

我试图设置一个rails应用程序,以便根据某些条件是否为真来选择不同的邮件传递方法。在运行期间在rails中切换邮件传递方法

所以,给出了两个交货方式:

ActionMailer::Base.add_delivery_method :foo 
ActionMailer::Base.add_delivery_method :bar 

我想我可以只创建一个电子邮件拦截器做这样的事情:

class DeliveryMethodChooser 
    def self.delivering_email(message) 
    if some_condition 
     # code to use mail delivery method foo 
    else 
     # code to use mail delivery method bar 
    end 
    end 
end 

的问题虽然是我不确定如何真正设置更改给定邮件的邮件传递方式。有任何想法吗?是否有可能动态选择使用什么delivery_method?

+0

什么是你想要的两种分娩方式? – s84

+0

我真的不知道这与问题有什么关系,但其中一个是:smtp via sendgrid,另一个将使用Amazon SES(使用mailchimp STS)。 – Frost

回答

7

因此,事实证明,您实际上可以将Proc作为默认参数传递给ActionMailer

它因此完全有可能做到这一点:

class SomeMailer < ActiveMailer::Base 
    default :delivery_method => Proc.new { some_condition ? :foo : :bar } 
end 

我不知道我真的知道我喜欢这个解决方案,但它工作的时间是和它只会是一个相对较短时间。

+0

无法在rails中工作4.1.4 – user1735921

14

你可以传递一个:DELIVERY_METHOD选项,以邮件的方法,以及:

def notification 
    mail(:from => '[email protected]',   
     :to => '[email protected]', 
     :subject => 'Subject', 
     :delivery_method => some_condition ? :foo : :bar) 
end 
+0

是的,当然,您可以这样做,因为您可以使用'default'方法设置默认的传递方法,我在我的答案中解释了这个方法。 – Frost

2

请注意,您也可以打开应用程序的配置动态地改变给药方法的应用范围:

SomeRailsApplication::Application.configure do 
    config.action_mailer.delivery_method = :file 
end 

例如,如果您在创建帐户时发送帐户确认电子邮件,则在db/seeds.rb中可能会有用。

+2

虽然这似乎并未改变所使用的方法。它会通过Rails.application.config.action_mailer.delivery_method报告新的方法 - 但仍然使用旧的(至少对我来说) – Kevin

+0

似乎也不适用于我。 – abhishek77in

3

您可以创建一个单独的ActionMailer子类,并改变DELIVERY_METHOD + smtp_settings这样的:

class BulkMailer < ActionMailer::Base 
    self.delivery_method = Rails.env.production? ? :smtp : :test 
    self.smtp_settings = { 
    address: ENV['OTHER_SMTP_SERVER'], 
    port:  ENV['OTHER_SMTP_PORT'], 
    user_name: ENV['OTHER_SMTP_LOGIN'], 
    password: ENV['OTHER_SMTP_PASSWORD'] 
    } 

    # Emails below will use the delivery_method and smtp_settings defined above instead of the defaults in production.rb 

    def some_email user_id 
    @user = User.find(user_id) 
    mail to: @user.email, subject: "Hello #{@user.name}" 
    end 
end