Email client with Python

To build email client, Python have built-in smtplib and email.message for sending emails. For receiving emails, we need to install imapclient and pyzmail36. You can install them using pip. This setup gives us both sending and inbox reading capabilities.”

Sending Email (SMTP)

Requirements:

//No need to install for sending — Python's built-in smtplib and email libraries are enough.

Example Code:

import smtplib
from email.message import EmailMessage

def send_email(sender, password, recipient, subject, body):
    msg = EmailMessage()
    msg['From'] = sender
    msg['To'] = recipient
    msg['Subject'] = subject
    msg.set_content(body)

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(sender, password)
        smtp.send_message(msg)
        print("Email sent!")

# Example use
send_email(
    sender='your_email@gmail.com',
    password='your_app_password',
    recipient='someone@example.com',
    subject='Hello from Python',
    body='This is a test email sent from a Python email client.'
)

Receiving Emails with IMAP

To read emails from an inbox you can use the IMAP protocol.

Requirements:

pip install imapclient pyzmail36

Example Code:

import imapclient
import pyzmail

def read_inbox(email, password, folder='INBOX'):
    imap = imapclient.IMAPClient('imap.gmail.com', ssl=True)
    imap.login(email, password)
    imap.select_folder(folder, readonly=True)

    uids = imap.search(['ALL'])  # You can also use ['UNSEEN']
    print(f"Found {len(uids)} messages in {folder}.")

    for uid in uids[-5:]:  # Read last 5 messages
        raw = imap.fetch([uid], ['BODY[]', 'FLAGS'])
        message = pyzmail.PyzMessage.factory(raw[uid][b'BODY[]'])

        print("From:", message.get_addresses('from'))
        print("Subject:", message.get_subject())

        if message.text_part:
            print("Body:", message.text_part.get_payload().decode(message.text_part.charset))
        print("-" * 50)

    imap.logout()

# Example use
read_inbox('your_email@gmail.com', 'your_app_password')

Read/Send Email example

Now we will create a small program to send and receive email. To make our program interactive, we create a simple menu where users can choose to send an email or read their inbox. This makes the script more user-friendly and practical.

Steps:

def menu():
    print("=== Python Email Client ===")
    print("1. Send Email")
    print("2. Read Inbox")
    choice = input("Choose (1 or 2): ")

    email = input("Your Email: ")
    password = input("App Password: ")

    if choice == '1':
        to = input("To: ")
        subject = input("Subject: ")
        body = input("Body: ")
        send_email(email, password, to, subject, body)
    elif choice == '2':
        read_inbox(email, password)
    else:
        print("Invalid option.")

menu()