How to detach mail attachments with Net::IMAP

Since documenattion on this topic is very "non existing" I thought I
would share this with you:

···

-------------------------------
require 'net/imap'

imap = Net::IMAP.new('my.mail.server')
imap.login('usr', 'pwd')
imap.select('Inbox')
# All msgs in a folder
msgs = imap.search(["SINCE", "1-Jan-1969"])
# Read each message
msgs.each do |msgID|
  msg = imap.fetch(msgID, ["ENVELOPE","UID","BODY"] )[0]
# Only those with 'SOMETEXT' in subject are of our interest
  if msg.attr["ENVELOPE"].subject.index('SOMETEXT') != nil
    body = msg.attr["BODY"]
    i = 1
    while body.parts[i] != nil
# additional attachments attributes
      cType = body.parts[i].media_type
      cName = body.parts[i].param['NAME']
      i+=1
# fetch attachment.
      attachment = imap.fetch(msgID, "BODY[#{i}]")[0].attr["BODY[#{i}]"]
# Save message, BASE64 decoded
      File.new(cName,'wb+').write(attachment.unpack('m'))
    end
  end
end
imap.close
---------------------------------

by
TheR

--
Posted via http://www.ruby-forum.com/.