The Doge Prince
The Doge Prince

Reputation: 468

Rails 3 ActionMailer corrupts 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.

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: "[email protected]"

    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)

Upvotes: 2

Views: 1235

Answers (1)

Kalman
Kalman

Reputation: 8121

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")

Upvotes: 7

Related Questions