Dynamically supply SMTP config in Rails

There are some scenarios where you need to dynamically set the SMTP config before sending out an E-mail. E.g.

  1. To let the users set their SMTP config via UI and store them in database.
  2. To support a multi-tenants system where each tenant has its own config.
  3. Use different set of config for different type of E-mail.

To do this, you can load the config dynamically before a mailer action is executed. Assuming you have a "Setting" table that store the SMTP config, you can read and set them when executing a mailer action. Example:

class UserMailer < ApplicationMailer
  def send_notification(user)
    mail from: read_setting_value('SMTP_FROM'), to: 'to_email', subject: 'Subject'
    set_smtp
  end

  private
  
  def set_smtp
    smtp_settings = {
      address: read_setting_value('SMTP_URL'),
      port: read_setting_value('SMTP_PORT').to_i,
      domain: read_setting_value('SMTP_DOMAIN'),
      user_name: read_setting_value('SMTP_USERNAME'),
      password: read_setting_value('SMTP_PASSWORD'),
      authentication: read_setting_value('SMTP_AUTHENTICATION'),
      enable_starttls_auto: true
    }

    mail.delivery_method.settings.merge!(smtp_settings.reject { |_k, v| v.blank? })
  end

  def read_setting_value(name)
    setting = Setting.find_by_name(name)
    setting&.value
  end
end

AI Summary
Chrome On-device AI 2024-07-20 06:18:36

Share Article