8.1 Reading Emails
I think we've got the basics of networking down. Let's do something more interesting — there's so much cool stuff on the net. How about reading and sending emails?
Email popped up 50 years ago, 20 years before the first browser. Back then, special programs were used to send mail. What does this mean for us? It means the standard (protocol) for working with email is as simple as pie.
The POP3
protocol (Post Office Protocol version 3) is used for retrieving email from a mail server. Unlike IMAP
, POP3
usually downloads emails to
a local computer and deletes them from the server. In Python, you can use the poplib
library to work with POP3
.
Note: Unlike POP3, the IMAP (Internet Message Access Protocol) allows you to store emails on the server and sync their state between devices. IMAP is more convenient if you read emails from different devices, while POP3 is better for storing emails locally on one device.
Basic steps to get a list of emails:
- Connect to the mail server.
- Authenticate.
- Get the list of emails.
- Download and read emails.
- Disconnect from the server.
For writing the first app, we'll need two libraries: poplib
and
email
. If you don't have them, install them. You already know how to use the pip
manager.
Important: Always follow security measures when working with email. Never store passwords in plain text in your code. Use environment variables or secure credentials storage. Also, make sure your code doesn't become publicly accessible to avoid leaking confidential information.
1. Connecting and authenticating:
Connect to the mail server via SSL
and log into your mailbox with
the specified credentials.
mailbox = poplib.POP3_SSL(pop3_server)
mailbox.user(username)
mailbox.pass_(password) # Use pass_ to avoid conflict with the pass keyword in Python
2. Getting mailbox information:
Get the number of emails in the mailbox.
num_messages = len(mailbox.list()[1])
print(f"Number of emails: {num_messages}")
3. Downloading and reading emails:
Load and read the last email.
# Example: Reading the last email
if num_messages > 0:
response, lines, octets = mailbox.retr(num_messages)
message = '\n'.join(line.decode('utf-8') for line in lines)
print("Content of the last email:")
print(message)
To parse and display the content, there's a special library —
email
. It can decode email content, attachments
including headers and body.
Here's what the final version of our email client might look like.
import poplib
# Login credentials
username = 'your_email@example.com'
password = 'your_password'
# Connect to Gmail's mail server
pop3_server = 'pop.gmail.com'
mailbox = poplib.POP3_SSL(pop3_server, 995)
# Log into the mailbox
mailbox.user(username)
mailbox.pass_(password) # Use pass_ to avoid conflict with the pass keyword in Python
# Get mailbox information
num_messages = len(mailbox.list()[1])
print(f"Number of emails: {num_messages}")
# Example: Reading the last email
if num_messages > 0:
response, lines, octets = mailbox.retr(num_messages)
message = '\n'.join(line.decode('utf-8') for line in lines)
print("Content of the last email:")
print(message)
# Close the connection
mailbox.quit()
Try reading your emails, just make sure to specify the correct
POP3 server
. In the example above, I listed Gmail's server info. If you have a different mail server, its details are easily googled online.
8.2 Sending Emails
To send emails using the
SMTP
(Simple Mail Transfer Protocol) in Python, you can
use the built-in smtplib
library. This module
provides functions to connect to an SMTP server
,
authenticate, and send emails.
Basic steps to send an email:
- Connect to the
SMTP server
. - Authenticate.
- Create the message.
- Send the message.
- Close the connection.
1. Connecting to the SMTP server
:
Connect to the SMTP server
and switch to a secure connection using
TLS
.
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Secure connection
2. Authentication:
Log in to the SMTP server
using credentials.
server.login(username, password)
3. Create a simple message as a string:
message = f"From: {from_addr}\nTo: {to_addr}\nSubject: {subject}\n\n{body}"
4. Send the message:
server.sendmail(from_addr, to_addr, message)
5. Close the connection:
server.quit()
Looks simpler than last time, which is a relief.
The entire code with error handling will look like this:
import smtplib
# Login credentials
smtp_server = 'smtp.gmail.com'
smtp_port = 587
username = 'your_email@gmail.com'
password = 'your_app_password' # Use an app password
# Sender and recipient addresses
from_addr = 'your_email@gmail.com'
to_addr = 'recipient@example.com'
# Subject and body of the email
subject = 'Email Subject'
body = 'This is the body of the email.'
# Create the message as a string
message = f"From: {from_addr}\nTo: {to_addr}\nSubject: {subject}\n\n{body}"
try:
# Connect to the SMTP server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Secure connection
# Authenticate
server.login(username, password)
# Send the message
server.sendmail(from_addr, to_addr, message)
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
finally:
# Close the connection
server.quit()
Most of the code here is comments and server setup, you can actually send an email in 5 lines. Give it a try — it's pretty cool.
GO TO FULL VERSION