How to read emails in Python

Published on Aug. 22, 2023, 12:17 p.m.

To read emails in Python, you can use the built-in poplib or imaplib modules, or you can use third-party libraries such as pyzmail, imapclient, or mail-parser. Here is an example of how to use the poplib module to read emails from a POP3 server:

import poplib
from email.parser import Parser
from email import policy

# Connect to the POP3 server
server = poplib.POP3_SSL('pop.example.com')
server.user('username')
server.pass_('password')

# Get the list of emails
num_messages = len(server.list()[1])
for i in range(num_messages):
    # Get the email by number
    response = server.retr(i+1)
    message = b'\n'.join(response[1]).decode('utf-8')

    # Parse the email message
    email = Parser(policy=policy.SMTP).parsestr(message)

    # Print the subject and sender
    print('Subject:', email['Subject'])
    print('From:', email['From'])

# Disconnect from the server
server.quit()

This example reads all the emails in the user’s inbox and prints the subject and sender for each email. You can modify the code to extract other parts of the email, such as the body or attachments.

To send emails in Python

To send emails in Python, you can use the built-in smtplib module or third-party libraries like yagmail or emails. Here is an example using smtplib:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

# Define the email content
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'Test email'
body = 'Hello, this is a test email.'
msg.attach(MIMEText(body, 'plain'))

# Add an attachment
with open('document.pdf', 'rb') as f:
    attachment = MIMEApplication(f.read(), _subtype='pdf')
    attachment.add_header('Content-Disposition', 'attachment', filename='document.pdf')
    msg.attach(attachment)

# Connect to the SMTP server
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'username'
smtp_password = 'password'
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)

# Send the email
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()

This example creates an email message with a plain text body and a PDF attachment, and sends it using an SMTP server. You will need to replace the SMTP server, port, username, and password with the values provided by your email provider.

Tags:

related content