Rails ActionMailer with multiple SMTP servers

前端 未结 11 1101
一整个雨季
一整个雨季 2020-12-13 06:19

I have a need to use two different smtp servers in a Rails application. It appears that the way ActionMailer is constructed, it is not possible to have different smtp_settin

11条回答
  •  佛祖请我去吃肉
    2020-12-13 07:14

    Based on the Oreilly article, I came up with the solution I wrote about here: http://transfs.com/devblog/2009/12/03/custom-smtp-settings-for-a-specific-actionmailer-subclass

    Here's the relevant code:

    class MailerWithCustomSmtp < ActionMailer::Base
      SMTP_SETTINGS = {
        :address => "smtp.gmail.com",
        :port => 587,
        :authentication => :plain,
        :user_name => "custom_account@transfs.com",
        :password => 'password',
      }
    
      def awesome_email(bidder, options={})
         with_custom_smtp_settings do
            subject       'Awesome Email D00D!'
            recipients    'someone@test.com'
            from          'custom_reply_to@transfs.com'
            body          'Hope this works...'
         end
      end
    
      # Override the deliver! method so that we can reset our custom smtp server settings
      def deliver!(mail = @mail)
        out = super
        reset_smtp_settings if @_temp_smtp_settings
        out
      end
    
      private
    
      def with_custom_smtp_settings(&block)
        @_temp_smtp_settings = @@smtp_settings
        @@smtp_settings = SMTP_SETTINGS
        yield
      end
    
      def reset_smtp_settings
        @@smtp_settings = @_temp_smtp_settings
        @_temp_smtp_settings = nil
      end
    end
    

提交回复
热议问题