Unicode in e-mail reading

while reading e-mails from gmail using imaplib and the code proposed here , the printed result showed encoded characters for accentuated letters or other languages like arabic.
this is the code :

import email
import imaplib
from bidi.algorithm import get_display
from email_config import gmail_pass, user, host
#email_config contents :
#gmail_pass = "**** **** **** ****"
#user = "user@gmail.com"
#host = "imap.gmail.com"
def read_email_from_gmail(count=3, contain_body=False):
    # Create server and login
    mail = imaplib.IMAP4_SSL(host)
    mail.login(user, gmail_pass)
    # Using SELECT to chose the e-mails.
    res, messages = mail.select('INBOX')
    # Caluclating the total number of sent Emails
    messages = int(messages[0])
    # Iterating over the sent emails
    for i in range(messages, messages - count, -1):
        # RFC822 protocol
        res, msg = mail.fetch(str(i), "(RFC822)")
        for response in msg:
            if isinstance(response, tuple):
                msg = email.message_from_bytes(response[1])
                # Store the senders email
                sender = msg["From"]
                # Store subject of the email
                subject = msg["Subject"]
                # Store Body
                body = ""
                temp = msg
                if temp.is_multipart():
                    for part in temp.walk():
                        ctype = part.get_content_type()
                        cdispo = str(part.get('Content-Disposition'))
                        # skip text/plain type
                        if ctype == 'text/plain' and 'attachment' not in cdispo:
                            body = part.get_payload(decode=True)  # decode
                    body = temp.get_payload(decode=True)
                # Print Sender, Subject, Body
                print("-"*50)  # To divide the messages
                print("From    : ", get_display(sender))
                print("Subject : ", get_display(subject))
                    #print("Body    : ", body.decode())
read_email_from_gmail(5, True)

and this is a sample output :

E-mail headers are encoded by quoted-printable or “Q” or “B” encoding:

Python standard library has functions for that:

1 Like

Thank you @vbrozik , i missed this point.