Skip to content
Advertisement

IMAP get sender name and body text?

I am using this code:

JavaScript

and it works, except, when I print raw_email it returns a bunch of extra information, how can I, parse, per say, the extra information and get just the From and body text?

Advertisement

Answer

Python’s email package is probably a good place to start.

JavaScript

That should do ask you ask, though when an email has multiple parts (attachments, text and HTML versions of the body, etc.) things are a bit more complicated.

In that case, msg.is_multipart() will return True and msg.get_payload() will return a list instead of a string. There’s a lot more information in the email.message documentation.

Alternately, rather than parsing the raw RFC822-formatted message – which could be very large, if the email contains attachments – you could just ask the IMAP server for the information you want. Changing your mail.fetch line to:

JavaScript

Would just request (and return) the From line of the email from the server. Likewise setting the second parameter to "(UID BODY[TEXT])" would return the body of the email. RFC2060 has a list of parameters that should be valid here.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement