Pythondex
Python Programs

Python Program For Email Header Analyzer

Last updated June 21, 2023 by Jarvis Silva

In this tutorial we will create a python program for email header analyzer, this program will print the basic details from the email head like message number, from, to, bcc, date and subject.

Inorder to create this program we will use the imaplib and email library which comes preinstalled with python so let’s code it.

Python Code For Email Header Analyzer


import imaplib
import email

imap_server = "imap.gmail.com"

# Enter your email here
email_address = "test@gmail.com"
# Enter your email password 
password = "test password"

imap = imaplib.IMAP4_SSL(imap_server)
imap.login(email_address,password)

imap.select("Inbox")

_, messageNums = imap.search(None,"ALL")

for messageNum in messageNums[0].split():
    _, data = imap.fetch(messageNum,"(RFC822)")
    message = email.message_from_bytes(data[0][1])

    print(f"Message number: {messageNum}")
    print(f"From: {message.get('From')}")
    print(f"To: {message.get('To')}")
    print(f"BCC: {message.get('BCC')}")
    print(f"Date: {message.get('Date')}")
    print(f"Subject: {message.get('Subject')}")

    print("Content: ")

    for part in message.walk():
        if part.get_content_type() == "text/plain":
            print(part.as_string())

imap.close()

Above is the code for analysing email header in python, in the program you need to enter your email and password then it will get your messages and print the details.

Now to run this program you need to have python installed on your computer, If you don’t have then follow this guide: Install and setup python on your computer.

After running this program you will see your email header details printed in the console window.

Here are some more python program tutorials for you:

I hope you found what you were looking for from this tutorial, and if you want more python programs and tutorials like this, do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂