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_settings for a subclass. I could reload the smtp settings for each mailer class whenever a message is being sent, but that messes up the ExceptionNotifier plugin which is outside my control (unless I mess with it too). Does anyone have a solution/plugin for something like this?
Ideally I would like to have
class UserMailer < ActionMailer::Base; end
and then set in environment.rb
ActionMailer::Base.smtp_settings = standard_smtp_settings
UserMailer.smtp_settings = user_smtp_settings
Thus, most of my mailers including ExceptionNotifier would pickup the default settings, but the UserMailer would use a paid relay service.
Based on the Oreilly article, I came up with the solution I wrote about here: http://transfs.com/devblog/2009/12/03/custom-smtp-settings-for-a-specific-actionmailer-subclass
Here's the relevant code:
class MailerWithCustomSmtp < ActionMailer::Base
SMTP_SETTINGS = {
:address => "smtp.gmail.com",
:port => 587,
:authentication => :plain,
:user_name => "[email protected]",
:password => 'password',
}
def awesome_email(bidder, options={})
with_custom_smtp_settings do
subject 'Awesome Email D00D!'
recipients '[email protected]'
from '[email protected]'
body 'Hope this works...'
end
end
# Override the deliver! method so that we can reset our custom smtp server settings
def deliver!(mail = @mail)
out = super
reset_smtp_settings if @_temp_smtp_settings
out
end
private
def with_custom_smtp_settings(&block)
@_temp_smtp_settings = @@smtp_settings
@@smtp_settings = SMTP_SETTINGS
yield
end
def reset_smtp_settings
@@smtp_settings = @_temp_smtp_settings
@_temp_smtp_settings = nil
end
end