
238 views
Python Email.utils
The email.utils
module in Python provides utility functions for parsing and formatting email addresses, dates, and other components commonly found in email messages. It’s part of the standard library and can be used to work with various email-related tasks.
Here are some common functions and classes available in the email.utils
module:
email.utils.parsedate(datestr, headertype='date')
: This function parses a date string typically found in email headers and returns a 9-tuple representing the date and time.headertype
can be one of ‘date’, ‘resent-date’, ‘orig-date’, or ‘expiry-date’.
Python
from email.utils import parsedate
datestr = 'Tue, 12 Oct 2021 15:30:00 +0300'
parsed_date = parsedate(datestr)
print(parsed_date)
email.utils.formatdate(timestamp=None, localtime=False, usegmt=False)
: This function returns a string representing the current date and time in RFC 2822 format. You can provide a custom timestamp or setlocaltime
orusegmt
to control how the date is formatted.
Python
from email.utils import formatdate
import time
timestamp = time.time()
formatted_date = formatdate(timestamp, localtime=True)
print(formatted_date)
email.utils.parseaddr(addr)
: This function parses an email address string and returns a tuple containing the display name and the actual email address.
Python
from email.utils import parseaddr
addr = 'John Doe <[email protected]>'
display_name, email_address = parseaddr(addr)
print(display_name)
print(email_address)
email.utils.formataddr(pair)
: This function formats a pair of (display_name, email_address) into a properly formatted email address string.
Python
from email.utils import formataddr
pair = ('John Doe', '[email protected]')
formatted_addr = formataddr(pair)
print(formatted_addr)
These are some of the commonly used functions in the email.utils
module for working with email-related data. This module can be helpful when dealing with email parsing and formatting tasks, especially when processing email messages in Python.