Search code examples
rubyemailrubygemsmail-gem

Trying to open / access the text in an attachment to an email using ruby gems


currently trying to write a code to extract text from a text file attachment in an email using ruby gems. Using the 'mail' gem.

this is what the code I found to isolate the body looks like:

mail = Mail.all
mail.each do |current_mail|
mail_object = Mail.read_from_string(current_mail)
puts mail_object.body
end

and this works good to find the body but when we attach a .txt file it returns this:

--_000_DM6PR04MB6138740F20BC287E0587E27281720DM6PR04MB6138namp_--

--_004_DM6PR04MB6138740F20BC287E0587E27281720DM6PR04MB6138namp_
Content-Type: text/plain;
name=readable.txt
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
creation-date="Mon, 27 Jul 2020 21:10:20 GMT";
filename=readable.txt;
 modification-date="Mon, 27 Jul 2020 21:10:22 GMT";
 size=16
Content-Description: readable.txt
Y2FuIHdlIHNlZSB0aGlzPw==
--_004_DM6PR04MB6138740F20BC287E0587E27281720DM6PR04MB6138namp_--

So I can see it has located the attachment name and file name but is there a way from here to access the text in this file?


Solution

  • The text file attachment will be Base64 encoded. So you should be able to just decode it like this.

    puts current_mail.attachments.each{|a| a.decode_body}
    =>"can we see this?"