The email
module in Python provides a comprehensive framework for managing email messages, including parsing, creating, and sending emails. It supports both simple text and more complex MIME (Multipurpose Internet Mail Extensions) messages, making it used for email handling.
Table of Contents
- Introduction
- Key Classes and Functions
email.message.EmailMessage
email.message.Message
email.mime.text.MIMEText
email.mime.multipart.MIMEMultipart
email.mime.base.MIMEBase
email.mime.application.MIMEApplication
email.parser
email.policy
email.utils
email.header
- Examples
- Creating a Simple Email
- Sending an Email
- Parsing an Email
- Creating a Multipart Email
- Adding Attachments
- Real-World Use Case
- Conclusion
- References
Introduction
The email
module in Python is designed to manage email messages. It includes classes and functions to create, manipulate, and parse email messages, both simple and complex. The module supports MIME standards, allowing for the creation and parsing of multimedia emails with attachments.
Key Classes and Functions
email.message.EmailMessage
The EmailMessage
class is the core class for creating email messages. It provides methods to create and manipulate email messages.
from email.message import EmailMessage
msg = EmailMessage()
email.message.Message
The Message
class is the base class for email messages.
from email.message import Message
msg = Message()
email.mime.text.MIMEText
The MIMEText
class is used to create text/plain or text/html email messages.
from email.mime.text import MIMEText
text = MIMEText('This is a plain text email', 'plain')
email.mime.multipart.MIMEMultipart
The MIMEMultipart
class is used to create multipart email messages.
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
email.mime.base.MIMEBase
The MIMEBase
class is the base class for all MIME-specific subclasses.
from email.mime.base import MIMEBase
mime = MIMEBase('application', 'octet-stream')
email.mime.application.MIMEApplication
The MIMEApplication
class is used to create application/* MIME types.
from email.mime.application import MIMEApplication
app = MIMEApplication(open('file.pdf', 'rb').read())
email.parser
The parser
module provides functions to parse email messages.
from email import parser
parsed_msg = parser.Parser().parsestr(raw_email_string)
email.policy
The policy
module defines policies for parsing and generating email messages.
from email import policy
email.utils
The utils
module provides various utility functions for email handling.
from email import utils
formatted_date = utils.formatdate(localtime=True)
email.header
The header
module provides classes to encode and decode email headers.
from email.header import Header
header = Header('Subject', 'utf-8')
Examples
Creating a Simple Email
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = 'Test Email'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg.set_content('This is a test email.')
print(msg)
Sending an Email
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = 'Test Email'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg.set_content('This is a test email.')
with smtplib.SMTP('smtp.example.com') as server:
server.login('username', 'password')
server.send_message(msg)
Parsing an Email
from email import parser
raw_email = """From: sender@example.com
To: recipient@example.com
Subject: Test Email
This is a test email.
"""
msg = parser.Parser().parsestr(raw_email)
print(msg['Subject'])
print(msg.get_payload())
Creating a Multipart Email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['Subject'] = 'Multipart Email'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
text = MIMEText('This is the plain text part of the email.', 'plain')
html = MIMEText('<html><body><h1>This is the HTML part of the email.</h1></body></html>', 'html')
msg.attach(text)
msg.attach(html)
print(msg)
Adding Attachments
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg['Subject'] = 'Email with Attachment'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
text = MIMEText('This email has an attachment.', 'plain')
msg.attach(text)
with open('file.pdf', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='pdf')
attachment.add_header('Content-Disposition', 'attachment', filename='file.pdf')
msg.attach(attachment)
print(msg)
Real-World Use Case
Sending Weekly Reports via Email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_weekly_report(subject, body, attachment_path, recipient):
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = 'sender@example.com'
msg['To'] = recipient
text = MIMEText(body, 'plain')
msg.attach(text)
with open(attachment_path, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='pdf')
attachment.add_header('Content-Disposition', 'attachment', filename=attachment_path)
msg.attach(attachment)
with smtplib.SMTP('smtp.example.com') as server:
server.login('username', 'password')
server.send_message(msg)
if __name__ == '__main__':
send_weekly_report(
subject='Weekly Report',
body='Please find the weekly report attached.',
attachment_path='weekly_report.pdf',
recipient='recipient@example.com'
)
Conclusion
The email
module in Python provides a robust framework for creating, parsing, and sending emails. With support for both simple text emails and complex MIME messages with attachments, it is used for managing email communications in Python applications.