1

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?

1 Answers1

1

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?"
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48
  • 1
    Yeah just needed a base 64 decode which I realized yesterday. I used : text = Base64.decode64 attachment.body.parts[1].body.raw_source – mozartsghost Jul 30 '20 at 15:50