Reading email using ruby-mail is not returning the mail body in text format

email, mail-gem, ruby, rubygems

Solution

The mail gem doesn't automatically decode the body. You can use:

mail.message.body.decoded

to get the decoded message body. In addition you might find that you want to access the plain of the HTML parts of a message. In order to do this you could use something like the following:

plain_part = message.text_part ? message.text_part.body.decoded : nil
html_part = message.html_part ? message.html_part.body.decoded : nil

You could then use the `message.body.decoded` as a fallback in case these parts don't exist.

Problem

Im using ruby-mail to read a email. Everything im getting in proper readable format, except mail body. Mail body appears as some other encoding format. My code is : ``` Mail.defaults do retriever_method :pop3, :address => "some.email.com", :port => 995, :user_name => 'domain/username', :password => 'pwd', :enable_ssl => true end puts "From" puts mail.from puts "Sender:" puts mail.sender puts "To:" puts mail.to puts "CC:" puts mail.cc puts "Subject:" puts mail.subject puts "Date:" puts mail.date.to_s puts "MessageID:" puts mail.message_id puts "Body:" #puts mail.body ``` Output is : From legalholdnotification123@emc.com Sender: To: bhavesh.sharma@emc.com CC: Subject: case4: Legal Hold Notification Date: 2012-04-24T14:46:25-04:00 MessageID: 3298720.1335293185423.JavaMail.root@vm-bhaveshok7 Body: Date: Sat, 05 May 2012 09:45:08 -0700 Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: base64 Content-ID: <4fa559147a120_138455aab4289ac@USITHEBBASL2C.mail> SGVsbG8gU2lyL01hZGFtLA0KDQpCcmllZiBpbnRyb2R1Y3Rpb24gdG8gdGhl IGNhc2UgY2FzZTQNCg0KV2UgaGF2ZSBpZGVudGlmaWVkIHlvdSBhcyBhIHBl cnNvbiB3aG8gbWF5IGhhdmUgImRvY3VtZW50cyIgLS0gd2hpY2ggaW5jbHVk ZXMgYm90aCBwaHlzaWNhbCBhbmQgZWxlY3Ryb25pYyBkb2N1bWVudHMgLS0g dGhhdCBhcmUgcmVsYXRlZCB0byB0aGlzIG1hdHRlci4gV2UgYXJlIGltcGxl bWVudGluZyBhIG1hbmRhdG9yeSBkb2N1bWVudCByZXRlbnRpb24gcG9saWN5 IHRvIHByZXNlcnZlIHRoZXNlIGRvY3VtZW50cy4gUGxlYXNlIGNhcmVmdWxs eSByZXZpZXcgdGhpcyBtZW1vcmFuZHVtIGFuZCBzdHJpY3RseSBhZGhlcmUg dG8gdGhlIG1hbmRhdG9yeSBkb2N1bWVudCByZXRlbnRpb24gcG9saWN5IG91 dGxpbmVkIGhlcmVpbi4gW0NvbXBhbnldIGNvdWxkIGJlIHN1YmplY3QgdG8g SO i cannot read the mail body. What needs to be done so that i can read the mail, i need to extract the text from the body and have to use the link that are present inside the mail body. Bhavesh

Original source