Rails:如何在运行时配置ActionMailer?

3
我想通过Gmail从我的应用程序发送少量电子邮件。现在,SMTP设置将在运行时确定(即:从数据库中),这可以完成吗?
--- 编辑 ---
我可以在类的一个方法中设置ActionMailer子类(名为Notifier)smtp设置。这样,我可以动态设置发送电子邮件的用户名和密码。唯一的问题是,您必须设置所有smtp_settings。是否可以仅在类方法中设置用户名和密码设置?
这是我现在正在使用的代码,它正在发送:
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

我只想在这里设置用户名和密码。

4个回答

2

(Rails 3)

由于我这样调用邮件程序:

CustomerMailer.customer_auto_inform(@form).deliver

在CustomerMailer类中,我有一个私有方法:
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

在调用发送电子邮件的 mail() 方法之前,您需要调用私有方法 init_email_account 来从数据库中填充 smtp_settings。 shop_mail 是存储邮件帐户设置数据的模型。
希望对您有所帮助。

0
假设您已经在环境或初始化器中配置了smtp_settings,那么您只需像这样设置用户名:
Notifier.smpt_settings.merge!({:user_name => "x", :password=> "y"})

0

你可以在控制器中这样做:

class ApplicationController < ActionController::Base

   ...

private

  def set_mailer_settings

    ActionMailer::Base.smtp_settings.merge!({
      username: 'username',
      password: 'yoursupersecretpassword'
    })

  end

end

1
这个方法可以运行,但是它不是线程安全的,所以要小心。 - Jay El-Kaake

0

由于配置文件都是Ruby编写的,因此可以轻松地在运行时从配置文件或类似文件中获取设置。

这是我之前写的一篇关于如何让ActionMailer与GMail SMTP配合使用的文章。

注意:如果您正在使用Rails 2.3和Ruby 1.87,则不需要插件,只需使用此评论中的设置即可。


1
是的,我看到了那个 :)我应该进一步解释一下,我需要能够在运行时动态设置帐户名和密码(即:从数据库中)...我想知道是否有一种简单的方法来实现它 :) - Fabian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接