I have a need to send mail from more than 1 SMTP account in Rails and
I stumbled upon this post
http://broadcast.oreilly.com/2009/03/using-multiple-smtp-accounts-w.html
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'',
:enable_starttls_auto => ''true'',
:port => 587,
:domain => ''mydomain.com'',
:authentication => :login,
:user_name =>
''errors-3Q2Tfjf0mexWk0Htik3J/w@public.gmane.org'',
: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?