Skip to content

Instantly share code, notes, and snippets.

@dnagir
Created February 10, 2012 03:38
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnagir/1786236 to your computer and use it in GitHub Desktop.
Save dnagir/1786236 to your computer and use it in GitHub Desktop.
Threaded mail delivery in rails
# lib/async_smtp_delivery_method.rb
require 'mail'
class AsyncSmtpDeliveryMethod
def initialize(settings)
@settings = settings
end
def deliver!(mail)
Thread.start do
begin
Mail::SMTP.new(@settings).deliver!(mail)
rescue Exception => ex
::Rails.logger.error "Failed to send email: #{ex.inspect}"
raise
end
end
end
end
ActionMailer::Base.add_delivery_method :async_smtp, AsyncSmtpDeliveryMethod
# KEPP IN MIND:
# It will only run as long as process does. So to test your email form rails runner add a wait period at exit, like this:
# rails runner "UserMailer.welcome.deliver; at_exit { sleep 15 }"
# environments/production.rb
require 'async_smtp_delivery_method'
YourApp::Application.configure do
config.action_mailer.delivery_method = :async_smtp
config.action_mailer.async_smtp_settings = {
:address => AppConfig.smtp.address,
:port => AppConfig.smtp.port,
:user_name => AppConfig.smtp.user_name,
:password => AppConfig.smtp.password,
:authentication => :plain,
:enable_starttls_auto => true
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment