Rails SMTP configuration in runtime

SMTP is mail delivery method in rails  which is used to send email through rails. Setting of SMTP is configured in different environment like development, production and test. For this we configure following setting in different file like config/environments/development.rb, config/environments/production.rb, config/environments/test.rb with respect to different environment.

 config.action_mailer.smtp_settings = {
   address: “smtp.gmail.com”,
   port: 587,
   domain: “mail.google.com”,
   user_name: “example@gmail.com”,
   password: “********”,
   authentication: “plain”,
   enable_starttls_auto: true

But sometime we need to set up smtp attributes like address, domain, port etc. dynamically on run time then these above method gives some problem. Because file on the config folder loaded when we start the server. For this we configure smtp settings in application controller. The configuration is as below.

before_filter :set_mailer_settings

def set_mailer_settings
  setting = MailerSetting.first()
  ActionMailer::Base.smtp_settings = {
    :address => setting.smpt_address,
    :port => setting.smtp_port,
    :domain => setting.smtp_domain,
    :authentication => setting.authentication_type,
    :user_name => setting.smtp_username,
    :password => setting.smtp_password

Where MailerSetting is a model from which attributes of smtp are fetch. By this way we can configure smtp setting dynamically in rails on run time.


Leave a Reply

Your email address will not be published. Required fields are marked *