IMAP : Fail to download Audio attachment in correct format

Hi All,

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

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.

~Rupak