【问题标题】:Rails: Runtime configuration of ActionMailer?Rails:ActionMailer 的运行时配置?
【发布时间】:2014-04-23 05:40:07
【问题描述】:

我想通过 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

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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    (轨道 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
    

    在调用发送电子邮件的 ma​​il() 之前,您需要调用私有方法 init_email_account 以从数据库中填充 smtp_settings。 shop_mail 是存储有关邮件帐户设置数据的模型。

    HTH

    【讨论】:

      【解决方案2】:

      由于配置文件都是 Ruby,因此可以在运行时轻松地从配置文件等中获取设置。

      这是我不久前在getting ActionMailer working with GMail SMTP 上写的帖子。

      注意:如果您使用的是 rails 2.3 和 Ruby 1.87,则不需要该插件,只需使用 this comment 中的设置即可

      【讨论】:

      • 是的,我已经看到了 :) 我应该进一步解释,我需要能够在运行时动态设置帐户名和密码(即:来自数据库)...我想知道如果有一个简单的方法来做到这一点:)
      【解决方案3】:

      假设您已经在您的环境或初始化程序中配置了 smtp_settings,您可以像这样设置用户名:

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

      【讨论】:

        【解决方案4】:

        您可以在控制器中执行此操作:

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

        【讨论】:

        • 这可行,但它不是线程安全的,所以要小心。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 2010-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多