【问题标题】:ActionMailer 2.3.5 mangles my zip attachmentActionMailer 2.3.5 破坏了我的 zip 附件
【发布时间】:2013-01-07 21:42:27
【问题描述】:

我正在尝试使用 ActionMailer 2.3.5 从 rails 发送带有 zip 附件的电子邮件。

服务器上的 zip 文件正常(使用 unzip 实用程序正确解压缩),但传递给收件人的 zip 文件已损坏。此外,添加附件会导致邮件中省略邮件正文。

这个方法没有什么特别之处:

attachment :content_type => "application/zip",
      :body => File.read(zip.path),
      :filename => File.basename(zip.path)

File.read 显然出了点问题。当我在这里传递一个字符串而不是文件内容时,附件会正确通过。与二进制数据有关吗?

WTF?

【问题讨论】:

  • 对电子邮件附件和原始 zip 文件进行了比较。文件结尾(317 字节)似乎被截断了。

标签: ruby-on-rails binary zip actionmailer


【解决方案1】:

问题在于File.read 将您的文件视为文本文件。 (我猜你是在 Windows 上尝试这个)你必须指定模式以强制它以二进制模式打开你的文件:

attachment :content_type => "application/zip",
  :body => File.read(zip.path, mode: 'rb'),
  :filename => File.basename(zip.path)

或者在 Rails > 3 中:

attachment[File.basename(zip.path)] = File.read(zip.path, mode: 'rb')

【讨论】:

    【解决方案2】:

    如果您想包含附件并保留您的正文(多部分邮件),您必须执行以下操作:

      def email(message)
        setup_mail(message)
    
        part       :content_type => "text/html", 
                   :body => render_message("email", @body)
    
        attachment :content_type => 'application/zip', 
                   :body => File.read(message[:file].path), 
                   :filename => File.basename(zip.path)
      end
    

    “电子邮件”是您的正文模板。

    【讨论】:

    • 谢谢——这解决了缺少邮件正文的问题。但是,Zip 文件仍然损坏。
    【解决方案3】:

    尝试指定附件的编码:

    attachment :content_type => "application/zip",
          :body => File.read(zip.path),
          :filename => File.basename(zip.path),
          :transfer_encoding => 'base64'
    

    【讨论】:

    • 感谢您的建议。不幸的是,zip文件仍然存在问题。干杯:)
    【解决方案4】:

    您可能需要以二进制读取模式打开压缩文件:

    :body => File.open(zip.path, 'rb') {|f| f.read}
    

    【讨论】:

      【解决方案5】:

      我在我的项目中遇到了同样的问题。我混合了“mu太短”和“fivaiez”的解决方案。现在它起作用了。非常感谢你们所有的cmets。以下是我的代码。

      def sent(sent_at = Time.now)
        subject    'test attachment mail'
        recipients 'mail-list@company.com'
        from       'please_no_reply@company.com'
        sent_on    sent_at
        content_type "text/html"
        attachment :content_type => 'application/zip',
                   :body => File.read("data/sample.zip"),
                   :filename => 'sample.zip',
                   :transfer_encoding => "base64"    
      end
      

      【讨论】:

        猜你喜欢
        • 2014-03-07
        • 2013-04-09
        • 1970-01-01
        • 2018-06-06
        • 1970-01-01
        • 2015-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多