Rails: setting ActionMailer runtime?

I would like to send a small number of letters from my application through Gmail. Now the SMTP settings will be determined at runtime (i.e. from db), can this be done?

--- change ---

I can set the smtp parameters of an ActionMailer subclass (named Notifier) ​​in one of the class methods. That way, I can set a username and password for sending emails dynamically. The only thing you need to set ALL smtp_settings. Is it possible to set only the username and password in the class method?

This is the code I'm using right now, it sends:

class Notifier < ActionMailer::Base def call(user) Notifier.smtp_settings = { :enable_starttls_auto => true, :address => "smtp.gmail.com", :port => "587", :domain => "mydomain.com", :authentication => :plain, :user_name => " fabian@mydomain.com ", :password => "password" } recipients user.email subject "Test test" body "Test" end end 

I would just like to specify the username and pw here.

+4
source share
4 answers

(Rails 3)

Since I call the mail program as follows:

 CustomerMailer.customer_auto_inform(@form).deliver 

In the CustomerMailer class, I have a private method:

 def init_email_account(shop_mail) ActionMailer::Base.raise_delivery_errors = true ActionMailer::Base.smtp_settings = { :address => shop_mail.address, :port => shop_mail.port, :domain => shop_mail.domain, :user_name => shop_mail.user_name, :password => shop_mail.password, :authentication => shop_mail.authentication.name, :enable_starttls_auto => shop_mail.enable_starttls_auto } end 

Before calling mail () , which sends the email, you need to call the private method init_email_account to populate smtp_settings from the database. shop_mail is a model that stores data about the settings of an email account.

NTN

+2
source

You can do this in the controller:

 class ApplicationController < ActionController::Base ... private def set_mailer_settings ActionMailer::Base.smtp_settings.merge!({ username: 'username', password: 'yoursupersecretpassword' }) end end 
+1
source

Since all configuration files are Ruby, then the settings can be easily extracted from the configuration file or the like. at runtime.

Here is a post I wrote some time ago to get ActionMailer to work with GMail SMTP .

NOTE. If you use rails 2.3 and Ruby 1.87, you don’t need a plugin and you can just use the settings in this comment

0
source

Assuming you configured smtp_settings in your environment or initializers, you can simply set the username like this:

 Notifier.smpt_settings.merge!({:user_name => "x", :password=> "y"}) 
0
source

All Articles