Rails ActionMailer with multiple SMTP servers

前端 未结 11 1107
一整个雨季
一整个雨季 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:22

    Solution for Rails 4.2+:

    config/secrets.yml:

    production:
      gmail_smtp:
        :authentication: "plain"
        :address: "smtp.gmail.com"
        :port: 587
        :domain: "zzz.com"
        :user_name: "zzz@zzz.com"
        :password: "zzz"
        :enable_starttls_auto: true
      mandrill_smtp:
        :authentication: "plain"
        :address: "smtp.mandrillapp.com"
        :port: 587
        :domain: "zzz.com"
        :user_name: "zzz@zzz.com"
        :password: "zzz"
        :enable_starttls_auto: true
      mailgun_smtp:
        :authentication: "plain"
        :address: "smtp.mailgun.org"
        :port: 587
        :domain: "zzz.com"
        :user_name: "zzz@zzz.com"
        :password: "zzz"
        :enable_starttls_auto: true
    

    config/environments/production.rb:

    config.action_mailer.delivery_method = :smtp
    config.action_mailer.smtp_settings = Rails.application.secrets.gmail_smtp
    

    app/mailers/application_mailer.rb:

    class ApplicationMailer < ActionMailer::Base
      default from: '"ZZZ" '
    
      private
    
      def gmail_delivery
        mail.delivery_method.settings = Rails.application.secrets.gmail_smtp
      end
    
      def mandrill_delivery
        mail.delivery_method.settings = Rails.application.secrets.mandrill_smtp
      end
    
      def mailgun_delivery
        mail.delivery_method.settings = Rails.application.secrets.mailgun_smtp
      end
    end
    

    app/mailers/user_mailer.rb:

    class UserMailer < ApplicationMailer
      # after_action :gmail_delivery, only: [:notify_user]
      after_action :mandrill_delivery, only: [:newsletter]
      after_action :mailgun_delivery, only: [:newsletter2]
    
      def newsletter(user_id); '...' end # this will be sent through mandrill smtp
      def newsletter2(user_id); '...' end # this will be sent through mailgun smtp
      def notify_user(user_id); '...' end # this will be sent through gmail smtp
    end
    

提交回复
热议问题