# How to detach mail attachments with Net::IMAP

**URL:** <https://www.ruby-forum.com/t/how-to-detach-mail-attachments-with-net-imap/106796>\
**Category:** Ruby\
**Created:** [June 14, 2007, 7:49am UTC](https://www.ruby-forum.com/t/how-to-detach-mail-attachments-with-net-imap/106796 "2007-06-14T07:49:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ther](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/977dab/32.png) [@ther](https://www.ruby-forum.com/u/ther)\
**Post date:** [June 14, 2007, 7:49am UTC](https://www.ruby-forum.com/t/how-to-detach-mail-attachments-with-net-imap/106796/1 "2007-06-14T07:49:32Z")

</div>

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
