【问题标题】:ActionMailer after_filter breaking content_typeActionMailer after_filter 破坏 content_type
【发布时间】:2014-03-07 05:20:06
【问题描述】:

[Rails 3.2.13] 我有一个基于 .text.erb.html.haml 模板发送隐式多部分电子邮件的邮件程序。没有问题。

我正在尝试添加一个 after_filter 以有条件地防止发送到无效电子邮件。根据this answer 和我读过的所有文档,这看起来很简单。

但是,包含此 after_filter 会将内容类型从 multipart/alternative 更改为 text/plain即使电子邮件有效。在文档中:“如果已将任何附件或部分添加到电子邮件中,则不会执行隐式模板渲染”。这适用于这里吗?这是预期的行为,还是我做错了什么?

把我的头撞到墙上,因为这看起来很简单。

class Notify < ActionMailer::Base

  include AbstractController::Callbacks

  after_filter :ensure_valid

  def some_email(user_id)
    @user = User.find(user_id)
    mail(to: @user.email)
  end

  ...

  private

  def ensure_valid
    if User.where(email: mail.to, invalid_email: true).any?
      mail.perform_deliveries = false
    end
    true
  end

end

编辑:经过更多修改,似乎在 after_filter 中调用mail 对象at all 会关闭多部分,即使是这样的:

def ensure_valid
  puts "mail: #{mail}"
  true
end

这是怎么回事?


尝试在 after_filter 中手动添加 content_type + 参数,例如

mail.content_type = 'multipart/alternative'
mail.header['Content-Type'].parameters[:boundary] = mail.body.boundary
mail.header['Content-Type'].parameters[:charset] = 'UTF-8' 

但无论出于何种原因,这似乎都不起作用。如果我只包含,它确实设置了 content_type

mail.content_type = 'multipart/alternative'

.. 但是我缺少边界和字符集参数。

我尝试过的其他不起作用的方法:

  • 在 environment.rb 中设置默认 content_type
  • 在邮件中设置默认 content_type

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 actionmailer


    【解决方案1】:

    仍然不完全确定这里发生了什么,但似乎在 after_filter 中使用 message 对象而不是 mail 可以解决此问题:

    def ensure_valid
      if User.where(email: message.to, invalid_email: true).any?
        message.perform_deliveries = false
      end
      true
    end
    

    这会正确设置 perform_deliveries 而不会影响 content_type(将其保留为 multipart/alternative)。奇怪的是所有示例都使用了mail 对象而不是message

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 2011-06-23
      • 2017-12-22
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多