Goal:
Getting the Html of an email looking exactly as in the mailbox saved as.html
Explanation: I am using Python and IMAP to download email and get the HTML content with .get_content_payload(text/HTML) but when I save it and open it, it doesn't look like the mail content as shown in the mailbox.
I tried writing an HTML file with mail_html but, it doesn't work out quite well as the CSS is missing the whole HTML email looks terrible. I want it to download along with other page assets. And here I need your help.
mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
mail.select(f'{TARGET}')
status, data = mail.search(None, 'ALL')
mail_ids = []
for block in data:
mail_ids += block.split()
for mail_id in mail_ids:
status, data = mail.fetch(mail_id, '(RFC822)')
print("BODY ENDS")
for response_part in data:
if isinstance(response_part, tuple):
message = email.message_from_bytes(response_part[1])
mail_from = message['from']
mail_subject = message['subject']
# if it is multi-part message separate first
if message.is_multipart():
mail_content = ''
mail_html = ' '
for part in message.get_payload():
# Get all parts of the message
if part.get_content_type() == 'text/plain':
mail_content += part.get_payload()
if message.get_content_type() == "text/html":
mail_html + part.get_payload()