# Problem reading attachments in emails

**URL:** <https://www.ruby-forum.com/t/problem-reading-attachments-in-emails/113833>\
**Category:** Rails\
**Created:** [September 5, 2007, 1:32pm UTC](https://www.ruby-forum.com/t/problem-reading-attachments-in-emails/113833 "2007-09-05T13:32:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ramya\_Addanki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/7c8e57/32.png) [@Ramya\_Addanki](https://www.ruby-forum.com/u/Ramya_Addanki)\
**Post date:** [September 5, 2007, 1:32pm UTC](https://www.ruby-forum.com/t/problem-reading-attachments-in-emails/113833/1 "2007-09-05T13:32:29Z")

</div>

I read the attachments in an email in the following manner:

def receive(email)  
base\_dir=“d:\temp\attachments”  
if email.has\_attachments?  
email.attachments.each do |a|  
filename=a.original\_filename  
File.open(base\_dir+“\”+filename,“w+”) { |f|  
puts f.syswrite(a.read) # i tried f.write also  
}  
end # end of attachments  
end # end if  
end # end def

The attachments are pdf files,images,.doc,.xls files.  
The problem now is the size of the files stored on the file system is  
the same as that of the attachment. But the data that gets written to  
the file is junk. Obviously i need to decode the content of the  
attachment. Any suggestion.

I did try to read the parts of the mail as described in the post:

> **[decoding email attachments with ActionMailer::Base receive | Plasticx Blog](http://plasti.cx/old/articles/2006/12/30/decoding-email-attachments-with-actionmailer-base-receive)**
>
> There are lots of references that say you can decode images and other media attachements in email using the \*receive\* method of \*ActionMailer::Base\* Ruby On Rai

but in this case, only 2 kb of data gets written

Any suggestions?

---

<div class="post-metadata">

**Author:** ![Ramya\_Addanki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/7c8e57/32.png) [@Ramya\_Addanki](https://www.ruby-forum.com/u/Ramya_Addanki)\
**Post date:** [September 5, 2007, 2:15pm UTC](https://www.ruby-forum.com/t/problem-reading-attachments-in-emails/113833/2 "2007-09-05T14:15:36Z")

</div>

Phew! Panicked too soon i guess, i figured what was wrong!  
Since the attachments were binary files, the mode should have been  
“wb”.  
After changing the mode, it works perfectly fine.

File.open(base\_dir+"\"+filename,“wb”)

/Ramya
