Search code examples
ruby-on-railsrubygmailzip

RoR - Download ZIP file using gmail gem


I am trying to set up some rake tasks. It requires me to connect to gmail and download a Zip file which is sent as an attachment.

I have written the following code(which works fine for downloading csv) -

gmail = Gmail.connect(ENV["USERNAME"], ENV["PASSWORD"])
msg = gmail.inbox.find(from: ENV["REC_USER"], 
  subject: args[:subject])
dir_path = "lib/mfu_payment_data/"
Dir.mkdir dir_path unless File.exists?(dir_path)

if msg.first
  msg.first.attachments.each do |attachment|
   File.write(File.join(dir_path,attachment.filename),attachment.body.decoded)
  end
end

It throws the following error -

rake aborted! 
Encoding::UndefinedConversionError: "\xED" from ASCII-8BIT to UTF-8

I assume that this has got something to do with the attachment.body.decoded, but I do not know how else to do this.


Solution

  • You can try writing the file in binary mode:

    File.open('/path/to/file;, 'wb') { |file| file.write(attachment.body.decoded) }
    

    "b" Binary file mode Suppresses EOL <-> CRLF conversion on Windows. And sets external encoding to ASCII-8BIT unless explicitly specified.

    The modes are described in the IO class which File inherits from.