简体   繁体   中英

Cannot send xlsx as attachment in Rails mailer

I am trying to send an email containing a file attachment created by the user.

attachments[document.display_name] =  File.read(document.public_filename)

This works in most conditions (including .docx, but fails for .xlsx files with the error:

invalid byte sequence in UTF-8

I am using attachment_fu to upload the attachments, and delayed_job to defer sending the emails, however the file I am trying to attach looks ok, and I can open it successfully outside the application.

I also saw a suggestion to change the code as follows, but it does not seem to help: include an extra.

    attachments[document.display_name] =  { :content => File.read(document.public_filename), :transfer_encoding => :binary }

How can I make the code work for all attachment types?

You need to specify the mode or encoding to let it read the file as binary:

attachments[document.display_name] =  File.read(document.public_filename, :mode => 'rb')

or

attachments[document.display_name] =  File.read(document.public_filename, :encoding => 'BINARY')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM