Using multiple SMTP accounts with Rails & ActionMailer

By Eric Berry
March 30, 2009 | Comments: 5

Recently I ran into a problem where I needed to be able to send emails via two different SMTP accounts within the same Rails application. I scoured the net trying to find a method to do this, but I couldn't find one. So I pulled out my hack-hat and got started.

If there are any better ways to do this, I would love to hear about it.

I first created a new YAML file in my config folder called action_mailer.yml. In this file, I specified three different nodes with the actionmailer settings.

Afterwards, I created two mailer models that represent each of the different mailers I will use.

app/models/mailer1.rb

app/models/mailer2.rb

So now when I send an email, I can first determine which mailer to use and then send the email.

For example, your controller might have code that looks like this:

I realize this is probably the hard way, but hey, it's a start. Please post any plugins or alternatives to doing this if you know of any.


5 Comments

What would you do if one needs to send emails from multiple accounts (more than 2) ? Creating n models is not very scalable.

I completely agree. I am still trying to find a solution to that problem. In fact, I am now in need of sending emails from 7 different mail accounts within the same Rails application. Does anyone else have ideas on how to make this work? If I come up with something, I'll post a follow-up.

4ex:


class TestMailer

def load_settings(site)
options = YAML.load_file("#{RAILS_ROOT}/config/test.yml")[RAILS_ENV][site]
@@smtp_settings = {
:address => options["address"],
:port => options["port"],
:domain => options["domain"],
:authentication => options["authentication"],
:user_name => options["user_name"],
:password => options["password"]
}
@template = site
end

def welcome_email(recipient, site, sent_at = Time.now)
load_settings(site)
@subject = "Thank you for visiting #{site}"
@recipients = RAILS_ENV == "production" ? recipient : "cavneb@gmail.com"
@from = 'gary@superfriends.com'
@sent_on = sent_at
end
end

This is exactly what i was searching, thanks for the code.

Amit

Nilesh:

You can use database to store multiple SMTP configuration. Then dynamically load settings.

i think this will suffice your need.

Amit

Leave a comment



Popular Topics

Browse Books

News Topics

Recommended for You


Got a Question?