Skip to content

Instantly share code, notes, and snippets.

@rohit9889
Created February 14, 2013 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rohit9889/4952491 to your computer and use it in GitHub Desktop.
Save rohit9889/4952491 to your computer and use it in GitHub Desktop.
Change SMTP Settings at runtime in your rails application
class MailSender
def self.send_mail(smtp_settings, user, mail_subject, mail_body)
options = { :address => smtp_settings["address"],
:domain => smtp_settings["domain"],
:port => smtp_settings["port"].to_i,
:user_name => smtp_settings["user_name"],
:password => smtp_settings["password"],
:authentication => smtp_settings["authentication"],
:enable_starttls_auto => true,
:openssl_verify_mode => 'none'
}
Mail.defaults do
delivery_method :smtp, options
end
mail = Mail.new do
from smtp_settings["user_name"]
to "#{user[:email]}"
subject mail_subject
html_part do
content_type 'text/html; charset=UTF-8'
body mail_body
end
end
mail.deliver!
end
end
class User < ActiveRecord::Base
before_create :send_activation_email
def send_activation_email
#.... Collect all your data
send_mail(mail_template, settings, mail_body)
end
def send_mail(mail_template, settings, mail_body)
smtp_settings = settings.smtp_settings
if smtp_settings.blank?
UserMailer.delay.activation_instructions(self, mail_template, mail_body)
else
MailSender.delay.send_mail(smtp_settings, self, mail_template["subject"], mail_body)
end
end
end
@andres99x
Copy link

Hey, is this thread safe?

Im looking for a way to set my smtp_settings dynamically and thread safe at the same time, since im running on puma, do you have any hints for me?

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment