Remember
An email message has headers and a body. Constructing a message is separate from sending it through an SMTP service.
An email message has headers and a body. Constructing a message is separate from sending it through an SMTP service.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
from email.message import EmailMessage
message = EmailMessage()
message["Subject"] = 'Welcome'
message.set_content("Hello, Ada!")
print(message["Subject"])
print(message.get_content().strip())Top-level scope
class EmailMessageObject 2 · EmailMessage<email.message.EmailMessage object>An email message has headers and a body. Constructing a message is separate from sending it through an SMTP service.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
from email.message import EmailMessage
message = EmailMessage()
message["Subject"] = 'Welcome'
message.set_content("Hello, Ada!")
print(message["Subject"])
print(message.get_content().strip())
|
v
DISPLAYED RESULT
Welcome
Hello, Ada!
FINAL BINDINGS
EmailMessage --> object 1 (type)
message --> object 2 (EmailMessage)
object 1: class EmailMessage
object 2: <email.message.EmailMessage object>Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
from email.message import EmailMessage
message = EmailMessage()
message["Subject"] = 'Welcome'
message.set_content("Hello, Ada!")
print(message["Subject"])
print(message.get_content().strip())Top-level scope
class EmailMessageObject 2 · EmailMessage<email.message.EmailMessage object>The example has finished. Compare the final output with the values and references above.
Welcome Hello, Ada!
What do you expect this program to print?
from email.message import EmailMessage
message = EmailMessage()
message["Subject"] = 'Welcome'
message.set_content("Hello, Ada!")
print(message["Subject"])
print(message.get_content().strip())Have you ever wanted your Python application to send an email—whether it’s a newsletter, a password reset link, or an alert from a monitoring system? This tutorial walks you through how to send emails using Python’s built-in smtplib and email libraries. No third-party packages required.
Before diving into code, it’s helpful to know how email sending works. Email clients (like Gmail or Outlook) use SMTP (Simple Mail Transfer Protocol) to send messages. Python’s smtplib allows you to interact with SMTP servers, and the email library helps you structure messages in a proper format.
Let’s start with the simplest example: sending a plain text email from a Gmail account.
import smtplib
from email.message import EmailMessage
# Setup email content
msg = EmailMessage()
msg['Subject'] = 'Test Email from Python'
msg['From'] = 'your_email@gmail.com'
msg['To'] = 'recipient@example.com'
msg.set_content('This is a test email sent from Python.')
# Gmail SMTP setup
smtp_server = 'smtp.gmail.com'
smtp_port = 587
# Send the email
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls() # Secure the connection
server.login('your_email@gmail.com', 'your_app_password')
server.send_message(msg)
print("Email sent successfully!")
Email sent successfully!
EmailMessage() – a modern way to create well-formatted email messages.starttls() – upgrades the connection to a secure encrypted one.You can send beautiful, formatted HTML emails as well. Let’s modify the previous example.
msg = EmailMessage()
msg['Subject'] = 'Welcome!'
msg['From'] = 'your_email@gmail.com'
msg['To'] = 'recipient@example.com'
html_content = """
<html>
<body>
<h1>Welcome to our service!</h1>
<p>We are thrilled to have you onboard.</p>
</body>
</html>
"""
msg.set_content('This is a fallback for non-HTML clients.')
msg.add_alternative(html_content, subtype='html')
HTML content sent as an email.
To include an attachment like a PDF or image, you can use the add_attachment() method. Here’s how to attach a PDF file:
from pathlib import Path
pdf_path = Path('sample.pdf')
pdf_data = pdf_path.read_bytes()
msg.add_attachment(pdf_data, maintype='application', subtype='pdf', filename='sample.pdf')
msg['From'] and login credentials match.It’s essential to wrap your email logic in try-except blocks to handle network errors or login failures gracefully.
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login('your_email@gmail.com', 'your_app_password')
server.send_message(msg)
except smtplib.SMTPAuthenticationError:
print("Login failed. Check your credentials.")
except Exception as e:
print(f"Something went wrong: {e}")
Login failed. Check your credentials.
For testing, Python offers a local debugging SMTP server that just prints emails instead of sending:
Run this in your terminal
python -m smtpd -c DebuggingServer -n localhost:1025
with smtplib.SMTP('localhost', 1025) as server:
server.send_message(msg)
Email content will be printed in the terminal running the dummy server.
starttls() or SMTP_SSL to keep your credentials safe.You can now build on this to send reports, alerts, or even newsletter campaigns using Python. Try integrating it with schedulers or form submissions for real-world automation!
Connect what you noticed in the example with the idea below.
An email message has headers and a body. Constructing a message is separate from sending it through an SMTP service.
Creating an EmailMessage automatically sends email.
This is the misconception to avoid.Reaching the recap and completing the quizzes are separate milestones.