Is it possible to get the body of emails using Python without having a header and footer attached? My current code is
import imaplib
username = "username"
password = "password"
imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
imap_server.login(username, password)
imap_server.select('INBOX')
def get_emails(email_ids):
"""
Takes in an array of email id's as input eg: ['1','7']
Returns an array of html strings corresponding to the given email id's"""
data = []
for e_id in email_ids:
status, response = imap_server.fetch(e_id, '(UID BODY[TEXT])')
data.append(response[0][1])
return data
An output HTML string is something like this:
--0016e6d9770b63df7104cebab205 Content-Type: text/plain; charset=ISO-8859-1
This is some html code
--0016e6d9770b63df7104cebab205 Content-Type: text/html; charset=ISO-8859-1 <html>
<body>
<p>This is some html code</p>
</body>
</html>
--0016e6d9770b63df7104cebab205--
Is it possible to just have the HTML without the headers? Example: I would like to see
<html>
<body>
<p>This is some html code</p>
</body>
</html>
as the output. Thanks!
You should use Python’s email support classes, such as email.parser to parse the message you’ve received, and then grab the appropriate MIME part. Alternatively, you can use IMAP’s BODYSTRUCTURE response and use that to figure out exactly which piece of the email you want to download.