Rails 3 ActionMailer损坏附件 [英] Rails 3 ActionMailer corrupts attachments

查看:109
本文介绍了Rails 3 ActionMailer损坏附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Rails 3.2.13 and have been following along with the ActionMailer guide (http://guides.rubyonrails.org/action_mailer_basics.html#sending-emails-with-attachments), but I'm having difficulty with sending email attachments.

执行后,电子邮件会正确发送,但附件始终会损坏。特别是,我看到了呈现的电子邮件和附件的正确文件名,但显示为无法打开的1KB文件。我在堆栈溢出和其他地方(例如 Rails 3:发送带有附件的邮件-首次发送后文件损坏发布了3.0.7 ActionMailer附件问题),但提供的所有解决方案均无济于事。我尝试了两种不同的传输方式(Gmail SMTP和Sendgrid),几种文件类型(png,pdf等),以及内联附件和普通附件,但始终具有相同的效果。

After execution the email sends properly but the attachment is always corrupted. In particular, I see the rendered email and the correct filename for the attachment but as a 1KB file that can't be opened. I've seen similar issues around stack overflow and elsewhere (e.g. Rails 3: Sending Mail with Attachment - corrupted file after first send and Rails 3.0.7 ActionMailer attachment issue), but none of the solutions offered have been able to help. I've tried two different transports (Gmail SMTP and Sendgrid), several file types (png, pdf, etc.), and both inline and normal attachments, but always with the same effect.

这是邮件程序的代码:

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

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

Where I'm calling it in my controller it looks like this (I'm using delayed_job here, but the attachment is corrupted even without it):

UserMailer.delay.welcome_email(@user)


推荐答案

显然,这是Windows(仅)读取(不读取)文件方式的行为。您需要同时指定 Windows中的Ruby的r(只读)和 b(二进制)可以正确读取。
http://ruby-doc.org/core-1.9。 3 / IO.html

Apparently, this is a Windows-only behavior in how the file is (not) read in. You need to specify both the "r" (read only) and "b" (binary) for Ruby in Windows to read it correctly. http://ruby-doc.org/core-1.9.3/IO.html

请参阅以下相关问题

将本地文件的内容读取到Rails中的变量中

尝试以下操作:

attachments ['logo_email.png'] =文件。 read( public / img / logo_email.png,模式: rb)

这篇关于Rails 3 ActionMailer损坏附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆