2011-07-04 35 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