Search code examples
ruby-on-rails-4smtpsendgridmailgun

Rails 4 multiple SMTP configurations


My rails 4 application works fine when using Mailgun or Sendgrid. I want to use both ex. When sending Orders to go through Sendgrid and when create Tickets to go through Mailgun.

I have both accounts and my config/environments/development.rb looks like:

 config.action_mailer.smtp_settings = {
    address: 'smtp.mailgun.org',
    port: 587,
    user_name: 'some_username',
    password: 'some_password',
    authentication: 'plain',
    enable_starttls_auto: true   }

If I replace with Sengrid smtp_settings it starts sending from Sendgrid but as I mentioned I want both and choose which one for specific function.

Thank you


Solution

  • for different environments you can set different email configurations

    in config/environments/staging.rb one mail service,

    in config/environments/production.rb second,

    and for config/environments/development.rb I suggest you to use letter_opener

    and after that in difference environment modes you will using appropriate mail settings

    EDIT

    I guess it's bad decision, but if you wanna send same mail via two mail services, you can redefine ActionMailer::Base.smtp_settings.

    Just create two mailers and redefine settings inside mailer :

    first

    class MailgunUserMailer < ApplicationMailer
      ActionMailer::Base.smtp_settings = {
          address: 'smtp.mailgun.org',
          port: 587,
          user_name: 'some_username',
          password: 'some_password',
          authentication: 'plain',
          enable_starttls_auto: true   }
    
      def created(@user)
        .....
    

    and second

    class MandrillUserMailer < ApplicationMailer
      ActionMailer::Base.smtp_settings = {
          address: 'smtp.mandrill.com',
          port: 587,
          user_name: 'some_username',
          password: 'some_password',
          authentication: 'plain',
          enable_starttls_auto: true   }
    
      def created(@user)
        .....
    

    and than you can send same email via 2 providers:

    MailgunUserMailer.created.deliver MandrillUserMailer.created.deliver