【问题标题】:Rails 3 ActionMailer corrupts attachmentsRails 3 ActionMailer 损坏附件
【发布时间】:2013-04-09 02:50:13
【问题描述】:

我正在使用 Rails 3.2.13 并且一直在遵循 ActionMailer 指南 (http://guides.rubyonrails.org/action_mailer_basics.html#sending-emails-with-attachments),但我在发送电子邮件附件时遇到了困难。

执行后,电子邮件正常发送,但附件始终损坏。特别是,我看到了呈现的电子邮件和附件的正确文件名,但它是一个无法打开的 1KB 文件。我已经在堆栈溢出和其他地方(例如Rails 3: Sending Mail with Attachment - corrupted file after first sendRails 3.0.7 ActionMailer attachment issue)看到过类似的问题,但所提供的解决方案都无法提供帮助。我尝试了两种不同的传输方式(Gmail SMTP 和 Sendgrid)、几种文件类型(png、pdf 等),以及内联附件和普通附件,但效果始终相同。

这是邮件程序的代码:

class UserMailer < ActionMailer::Base

    # A hash of default values for email messages
    default from: "me@mysite.com"

    def welcome_email(user)
        @user = user
        @url = "http://localhost:3000"

        attachments['logo_email.png'] = File.read("public/img/logo_email.png")

        mail(:to => user.email, :subject => "Welcome")
    end
end

我在我的控制器中调用它的地方看起来像这样(我在这里使用delayed_job,但即使没有它,附件也会损坏):

UserMailer.delay.welcome_email(@user)

【问题讨论】:

  • 这也发生在我身上.. :S 你解决了吗?
  • @Lichtamberg 不幸的是,没有。 :( 我最近也没有使用 Rails,所以我没有回去再看一下。

标签: ruby-on-rails ruby actionmailer


【解决方案1】:

显然,在文件被(不)读入时,这是一个仅限 Windows 的行为。您需要为 Windows 中的 Ruby 指定“r”(只读)和“b”(二进制)才能读取它正确。 http://ruby-doc.org/core-1.9.3/IO.html

查看以下相关问题

Read contents of a local file into a variable in Rails

尝试以下方法:

attachments['logo_email.png'] = File.read("public/img/logo_email.png", mode: "rb")

【讨论】:

  • 谢谢,帮我修好了!
猜你喜欢
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2013-03-18
  • 1970-01-01
相关资源
最近更新 更多