Load SMTP setting dynamically

(1) Default or common settings are still kept in the initializer. E.g.

ActionMailer::Base.smtp_settings = {
    :enable_starttls_auto => true
}

(2) Create a private method in the mailer to read credential dynamically.

  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')
    }

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

(3) Call this method from your mailer action. E.g.

  def invite_user(user)
    @user = user
    mail(to: @user.email, subject: 'Your Invitation')
    set_smtp
  end

AI Summary
Chrome On-device AI 2024-07-20 04:50:26

Share Article