Skip to main content
The email package provides tools for managing email messages, including MIME and other RFC 2822-based message documents.

Module Import

from email.message import EmailMessage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import smtplib

Creating Email Messages

Simple Text Email

from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'Hello'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.set_content('This is the email body.')

print(msg.as_string())

HTML Email

from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'HTML Email'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'

msg.set_content('Plain text version')  # Fallback
msg.add_alternative("""
<html>
  <body>
    <h1>Hello!</h1>
    <p>This is an <b>HTML</b> email.</p>
  </body>
</html>
""", subtype='html')

Email with Attachment

from email.message import EmailMessage
import os

msg = EmailMessage()
msg['Subject'] = 'File Attached'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.set_content('Please find attached file.')

# Attach file
with open('document.pdf', 'rb') as f:
    file_data = f.read()
    file_name = os.path.basename('document.pdf')

msg.add_attachment(file_data, maintype='application', 
                   subtype='pdf', filename=file_name)

Sending Email

Using SMTP

from email.message import EmailMessage
import smtplib

# Create message
msg = EmailMessage()
msg['Subject'] = 'Test Email'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.set_content('Test message body')

# Send via SMTP
with smtplib.SMTP('smtp.example.com', 587) as smtp:
    smtp.starttls()  # Enable encryption
    smtp.login('username', 'password')
    smtp.send_message(msg)

print('Email sent successfully')

Using Gmail

from email.message import EmailMessage
import smtplib

msg = EmailMessage()
msg['Subject'] = 'Gmail Test'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.set_content('Email sent via Gmail')

# Send via Gmail SMTP
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login('[email protected]', 'your-app-password')
    smtp.send_message(msg)

Parsing Email Messages

from email import message_from_string
from email.policy import default

email_text = """From: [email protected]
To: [email protected]
Subject: Test

Email body content.
"""

msg = message_from_string(email_text, policy=default)

print(f"From: {msg['From']}")
print(f"To: {msg['To']}")
print(f"Subject: {msg['Subject']}")
print(f"Body: {msg.get_content()}")

MIME Multipart

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

# Create multipart message
msg = MIMEMultipart()
msg['Subject'] = 'Multipart Message'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'

# Add text part
text = MIMEText('This is the text part.', 'plain')
msg.attach(text)

# Add HTML part
html = MIMEText('<h1>HTML Part</h1>', 'html')
msg.attach(html)

# Add image
with open('image.jpg', 'rb') as f:
    img = MIMEImage(f.read())
    img.add_header('Content-Disposition', 'attachment', filename='image.jpg')
    msg.attach(img)

Practical Example

Email Utility Class

from email.message import EmailMessage
import smtplib
from pathlib import Path

class EmailSender:
    def __init__(self, smtp_server, smtp_port, username, password):
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.username = username
        self.password = password
    
    def send_email(self, to, subject, body, attachments=None, html=False):
        msg = EmailMessage()
        msg['Subject'] = subject
        msg['From'] = self.username
        msg['To'] = to
        
        if html:
            msg.set_content(body)  # Plain text fallback
            msg.add_alternative(body, subtype='html')
        else:
            msg.set_content(body)
        
        # Add attachments
        if attachments:
            for attachment in attachments:
                path = Path(attachment)
                with path.open('rb') as f:
                    msg.add_attachment(f.read(),
                                     maintype='application',
                                     subtype='octet-stream',
                                     filename=path.name)
        
        # Send email
        with smtplib.SMTP(self.smtp_server, self.smtp_port) as smtp:
            smtp.starttls()
            smtp.login(self.username, self.password)
            smtp.send_message(msg)

# Usage
sender = EmailSender('smtp.gmail.com', 587, 
                     '[email protected]', 'your-password')

sender.send_email(
    to='[email protected]',
    subject='Test Email',
    body='<h1>Hello!</h1><p>This is a test.</p>',
    html=True,
    attachments=['document.pdf', 'image.jpg']
)
For Gmail, use an App Password instead of your regular password for better security.
Never hardcode email credentials in your source code. Use environment variables or secure credential storage.

smtplib

SMTP protocol client

json

JSON encoding/decoding

Build docs developers (and LLMs) love