# Using multiple SMTP accounts with Rails & ActionMailer

**URL:** <https://www.ruby-forum.com/t/using-multiple-smtp-accounts-with-rails-actionmailer/177987>\
**Category:** Rails\
**Created:** [October 27, 2009, 3:42pm UTC](https://www.ruby-forum.com/t/using-multiple-smtp-accounts-with-rails-actionmailer/177987 "2009-10-27T15:42:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tnyplz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/f17d59/32.png) [@tnyplz](https://www.ruby-forum.com/u/tnyplz)\
**Post date:** [October 27, 2009, 3:42pm UTC](https://www.ruby-forum.com/t/using-multiple-smtp-accounts-with-rails-actionmailer/177987/1 "2009-10-27T15:42:15Z")

</div>

I have a need to send mail from more than 1 SMTP account in Rails and  
I stumbled upon this post

> **[Radar - O’Reilly](https://www.oreilly.com/radar/)**
>
> Now, next, and beyond: Tracking need-to-know trends at the intersection of business and technology

The Author wasn’t thrilled with his solution and I’m hoping this forum  
can come up with something a little cleaner.

I took a different approach (that I’m not in love with either).

I created and email config class that sets the smtp settings for a  
specific configuration, does a yield call (to deliver the mail) and  
then replaces the base settings. This ensures that code that is  
happy with the default settings will use them without needing a code  
change.

====== email\_config.rb ============  
class EmailConfig  
@@the\_map = {}  
def self.set\_config(name, mapping)  
@@the\_map[:base] = ActionMailer::Base.smtp\_settings if @@the\_map  
[:base].blank?  
@@the\_map[name] = mapping  
end  
def self.run\_with\_config(name)  
ActionMailer::Base.smtp\_settings = @@the\_map[name] if @@the\_map  
[name]  
begin  
RAILS\_DEFAULT\_LOGGER.debug(“EMAIL send as #  
{ActionMailer::Base.smtp\_settings[:user\_name]}”)  
yield  
ensure  
ActionMailer::Base.smtp\_settings = @@the\_map[:base] if @@the\_map  
[:base]  
RAILS\_DEFAULT\_LOGGER.debug(“EMAIL sent now configured for #  
{ActionMailer::Base.smtp\_settings[:user\_name]}”)  
end  
end  
end

Now in an after\_initialize block in production.rb I can set the  
following

EmailConfig.set\_config(:exception, {  
:address =\> ‘[smtp.gmail.com](http://smtp.gmail.com)’,  
:enable\_starttls\_auto =\> ‘true’,  
:port =\> 587,  
:domain =\> ‘[mydomain.com](http://mydomain.com)’,  
:authentication =\> :login,  
:user\_name =\> ‘removed\_email\_address@domain.invalid’,  
:password =\> ‘passwd’  
})

In my case I wanted emails from the exception notification plugin to  
goto a different email address. I needed to modify the  
deliver\_exception\_notification call to the following

EmailConfig.run\_with\_config(:exception){  
ExceptionNotifier.deliver\_exception\_notification(exception,  
self,  
request, data)}

It works fine but I’m wondering if there is a cleaner way to do this.  
Thoughts?
