2

I am using IMAP apis to access my mailbox and download attachments (.wav audio file) if any. After saving the attachment, I expect it to be a valid .wav file which I could play, but it gives me invalid file.

When I save the attachment after decoding (mail.attachments.first.decoded), it has the following contents:

  X-MCPBodyContent: --- 
  duration: 5
  internal_codec: alaw
  external_codec: wav
  type: 1
  filename: /9/04/04/04/05/m_88888_56b07809-1fe6-4cf7-8328-8e9bb0bd7716
  $$$$$

If I save the attachment as it is (mail.attachments.first), it has the following:

  Date: Tue, 18 Oct 2011 09:06:07 -0400
  Mime-Version: 1.0
  Content-Type: audio/wav;
    charset=UTF-8
  Content-Transfer-Encoding: base64
  Content-Disposition: attachment;
   filename=m_88888_56b07809-1fe6-4cf7-8328-8e9bb0bd7716.wav
  Content-ID: <4e9d79bfa830f_7efc3f9579013bfc3648e@vavcafeserver2.mail>

  WC1NQ1BCb2R5Q29udGVudDogLS0tIApkdXJhdGlvbjogNQppbnRlcm5hbF9j
  b2RlYzogYWxhdwpleHRlcm5hbF9jb2RlYzogd2F2CnR5cGU6IDEKZmlsZW5h
  bWU6IC85LzA0LzA0LzA0LzA1L21fODg4ODhfNTZiMDc4MDktMWZlNi00Y2Y3
  LTgzMjgtOGU5YmIwYmQ3NzE2CiQkJCQk

Here is the code snippet:

require 'net/imap'
imap = Net::IMAP.new('the_url', 143, false, nil, false) 
imap.login('username', 'password') 
imap.select('Inbox') 
# All msgs in a folder 
msgs = imap.uid_search(["ALL"]) 

# Read each message 
msgs.each do |uid| 
  _body = imap.uid_fetch(uid, "RFC822")[0].attr["RFC822"]

  require 'mail'
  mail = Mail.new(_body)

  attachment = mail.attachments.first
  fn = attachment.filename
  begin
    File.open( fn, "w+b", 0644 ) { |f| f.write attachment.decoded}
  rescue Exception => e
    puts "Error : Unable to save data for #{fn} because #{e.message}"
  end
end  
imap.logout

Please let me know how to get the attachment in correct format.

Any help would highly be appreciated.

Thanks

RupakSah
  • 31
  • 4

2 Answers2

2

Following works for me - tested with mp3, jpg and pdf files.

new_mail = imap.search(["ALL"]).each do |uid|
  body = imap.fetch(uid, "BODY[]")[0].attr["BODY[]"]
  mail = Mail.new(body)
  mail.attachments.each do |a|
      File.open("/home/vknoll/Downloads/imap/#{a.filename}", 'wb') do |file|
        file.write(a.body.decoded)
      end
  end
end
0

I haven't tried it, but is it worth closing the file in an ensure block? It may well be that this is required to flush the stream out to disk.

hcarver
  • 7,126
  • 4
  • 41
  • 67
  • 2
    The File.open block automatically closes the file for you. http://stackoverflow.com/a/4795782/226255 – Abdo Jan 22 '14 at 12:47