Rails 3 ActionMailer corrupts attachments

百般思念 提交于 2019-12-12 21:58:08

问题


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.

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.

Here's the code for the mailer:

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

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)

回答1:


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

See the following related issue

Read contents of a local file into a variable in Rails

Try the following:

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



来源:https://stackoverflow.com/questions/16041452/rails-3-actionmailer-corrupts-attachments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!