Electronic mail (email) is a commonly used way to communicate messages between two devices connected on the internet nowadays. An email has evolved over time from being only comprised of ASCII text message to message with different types of data (HTML, audio, video, images, pdf files, etc).
Python provides a module named email which lets us represent an email in python using an object.
The email module tries to be as compliant as possible to RFC 5233 and RFC 6532 to represent an email message.
The email module does not provide us with the functionality to send emails or retrieve emails from the server. Python provides other modules like smtplib and imaplib for these purposes (links provided below).
The email library just provides us with an API that lets us creates an object to represent an email message. These objects can then used by smtplib for sending mail. It also provides an API that lets us create an object representing email from string or bytes string.
As a part of this tutorial, we have explained how to create email message objects using an API provided by Python module "email" with simple and easy-to-understand examples. We have explained things like how to add CC / BCC details to mail, add http headers, add attachments, etc. We have also explained at last how we can send emails that we created and how we can convert bytes string to email object with single examples each.
If you are looking for guidance on how to perform operations with mailboxes like read emails, delete emails, star / flag emails, list directories, create directories, delete directories, search emails (w / wo pattern), etc then please check below link. As we mentioned earlier, we need to use IMAP protocol for interacting with mailboxes.
Below, we have listed important sections of tutorial to give an overview of the material covered.
As a part of our first example, we'll explain how we can represent a simple text message using EmailMessage object of message sub-module of email module.
EmailMessage() -The message submodule of email module provides us with a class named EmailMessage which can be used to represent an email message. It has a list of methods that let us set contents of the mail, headers of the mails, add attachments to it, etc.
The EmailMessage instance works like a dictionary which let us retrieve and set header value by using brackets as we do with a dictionary. It handles case-related mistakes in header names when matching (if you give from or From as key, then in both cases it'll retrieve Form header value).
Our code for this example starts by creating an instance of EmailMessage. It then adds headers From, To and Subject to the email. We are then setting the string as the content of the email. We are then generating string and bytes string representation of the email and printing them.
We can easily send email represented by EmailMessage instance using smtplib library's send_message() method. Please feel free to check our tutorial on smtplib if you are interested in learning about how to send mail using Python. There is an example later in this tutorial explaining how to send mail.
import email
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in, mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
############# Retrieve Message as a String ################
message_as_string = message.as_string()
print("\n============ Message as String ==============")
print(message_as_string)
############# Retrieve Message as a Byte String ################
message_as_bytes = message.as_bytes()
print("\n============ Message as Bytes ==============")
print(message_as_bytes)
As a part of our second example, we are demonstrating how we can add Cc and Bcc fields to our mail. We can add them using add_header() method as explained below.
All of our remaining code is the same as our previous example with only the addition of two lines for Cc and Bcc headers.
import email
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
############# Retrieve Message as a String ################
message_as_string = message.as_string()
print("\n============ Message as String ==============")
print(message_as_string)
print("\n========== Message Content ==================")
print(message.get_content())
As a part of our third example, we are demonstrating how we can clear the contents of the mail (body part) and how we can clear contents and headers both using clear_content() and clear() methods of EmailMessage instance.
Our code for this example is almost the same as our previous example. We start by creating an instance of EmailMessage and add headers to it. We also set the body part of the message using set_content() method. We are then printing mail as a string. We are then calling clear_content() method and then printing the mail as a string. At last, we are calling clear() method and printing the mail as a string again.
import email
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
############# Retrieve Message as a String ################
message_as_string = message.as_string()
print("\n============ Message as String ==============")
print(message_as_string)
message.clear_content()
print("\n========== Message as String ==================")
print(message.as_string())
message.clear()
print("\n========== Message as String ==================")
print(message.as_string())
We'll use our fourth example to demonstrate how we can access details of the headers of the mail in a different way using different methods of EmailMessage instance.
Our code for this example starts by creating an instance of EmailMessage and then adds headers to it. It then adds the contents of the body of the message. We then print the mail as a string. We are then printing details of headers of the message using items() method.
After that, we are printing header details of the mail using keys() and get() methods. At last, we are printing details of the headers using keys() method to retrieve header name and treating EmailMessage instance as a dictionary to retrieve header value. We are also calling values() method, at last, to print a list of header values for explanation purposes.
import email
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
############# Retrieve Message as a String ################
message_as_string = message.as_string()
print("\n============ Message as String ==============")
print(message_as_string)
print("\n=========== Headers using items() ================")
for header,value in message.items():
print("{:25s} - {}".format(header, value))
print("\n=========== Headers using keys() & get() ================")
for header in message.keys():
print("{:25s} - {}".format(header, message.get(header)))
print("\n=========== Headers using keys() ================")
for header in message.keys():
print("{:25s} - {}".format(header, message[header]))
print("\nHeader Values : {}".format(message.values()))
As a part of our fifth example, we'll demonstrate how we can set and retrieve the content type of the mail using various methods of EmailMessage instance.
Our code for this example like our previous example creates an instance of EmailMessage, sets headers, sets contents of the mail, and then prints email as a string. We are then calling all methods mentioned above to check the content types of the mail. We have also called set_default_type() to set content type of the mail as text/plain.
Python provides a module named "mimetypes" that can be used to retrieve MIME type of files. Please check below link for more details. We have also explained its usage in our next example.
import email
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
message.set_default_type("text/plain")
############# Retrieve Message as a String ################
message_as_string = message.as_string()
print("\n============ Message as String ==============")
print(message_as_string)
print("\n========= Content Type Details ==============")
print("Content Type : {}".format(message.get_content_type()))
print("Content Main Type : {}".format(message.get_content_maintype()))
print("Content Sub Type : {}".format(message.get_content_subtype()))
print("Content Default Type : {}".format(message.get_default_type()))
print("Is Attachment? : {}".format(message.is_attachment()))
print("Is Multipart? : {}".format(message.is_multipart()))
As a part of our sixth example, we are demonstrating how we can add attachments to the mail and then retrieve the body part of the mail. The mail becomes multipart once we add an attachment to it.
Our code for this example uses mimetypes module to retrieve the MIME content type of the attachment file. We are attaching a JPEG image file as an attachment.
We are first retrieving the MIME type of the attachment using guess_type() method of mimetypes module.
We are then reading the contents of the JPEG image file as bytes and calling add_attachment() method to add an image as an attachment. We have passed the main type, subtype, and file name details for the attachment along with the data.
We are then printing the content type of the mail. We are then calling get_body() method to retrieve the mail part which represents the actual body part of the mail and printing body contents.
import mimetypes
import email
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
############# Add Attachments #############################
mime_type, encoding = mimetypes.guess_type("dr_apj_kalam.jpeg")
print("MIME Type of JPEG File : {}".format(mime_type))
with open("dr_apj_kalam.jpeg", "rb") as fp:
image_data = fp.read()
message.add_attachment(image_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="kalam.jpeg")
########################## Content Type #################
print("\nContent Type : {}".format(message.get_content_type()))
print("Is Multipart? : {}".format(message.is_multipart()))
#################### Message body ################
m = message.get_body()
print("\nMessage Body Type : {}".format(type(m)))
print("\n========= Message Body ===========")
print(m.get_content())
As a part of our seventh example, we'll explain how we can iterate through the list of attachments present in the mail using iter_attachments() method of EmailMessage instance.
Our code for this example uses much of the code that we have been using for the last many examples. We are adding three attachments (JPEG image, PDF file, and Zip file) to our mail as a part of the code. We are then retrieving each attachment using iter_attachments() methods and printing their information like content type, content-disposition, etc.
import mimetypes
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
############# Add Attachments #############################
######### JPEG File ##################
mime_type, encoding = mimetypes.guess_type("dr_apj_kalam.jpeg")
print("MIME Type of JPEG File : {}".format(mime_type))
with open("dr_apj_kalam.jpeg", "rb") as fp:
image_data = fp.read()
message.add_attachment(image_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="kalam.jpeg")
############ PDF File ######################
mime_type, encoding = mimetypes.guess_type("Deploying a Django Application to Google App Engine.pdf")
print("MIME Type of PDF File : {}".format(mime_type))
with open("Deploying a Django Application to Google App Engine.pdf", "rb") as fp:
pdf_data = fp.read()
message.add_attachment(pdf_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="gcloud.pdf")
############ Zip File ######################
mime_type, encoding = mimetypes.guess_type("docs.zip")
print("MIME Type of ZIP File : {}".format(mime_type))
with open("docs.zip", "rb") as fp:
image_data = fp.read()
message.add_attachment(image_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="docs.zip")
########################## Content Type #################
print("\nContent Type : {}".format(message.get_content_type()))
print("Is Multipart? : {}".format(message.is_multipart()))
print("Content Disposition : {}".format(message.get_content_disposition()))
################# Attachments #####################
print("\n================ Attachments ===================")
for attachment in message.iter_attachments():
print("\nAttachment Type : {}".format(type(attachment)))
print("Content Type : {}".format(attachment.get_content_type()))
print("Is Multipart? : {}".format(attachment.is_multipart()))
print("Is Attachment? : {}".format(attachment.is_attachment()))
print("Content Disposition : {}".format(attachment.get_content_disposition()))
As a part of our eighth example, we are demonstrating how we can iterate over sub-parts of the mail using iter_parts() method of EmailMessage instance.
Our code for this example is almost the same as our code from our previous example. We are adding three attachments to our mail like our previous example. We are then retrieving sub-parts of the mail using iter_parts() method and printing their details like content type, disposition, etc. We can notice from the output that, this method returns one extra message part (along with attachments), which is of type text/plain and represent the body part of the message. The main message is of type multipart/mixed.
import mimetypes
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
############# Add Attachments #############################
######### JPEG File ##################
mime_type, encoding = mimetypes.guess_type("dr_apj_kalam.jpeg")
print("MIME Type of JPEG File : {}".format(mime_type))
with open("dr_apj_kalam.jpeg", "rb") as fp:
image_data = fp.read()
message.add_attachment(image_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="kalam.jpeg")
############ PDF File ######################
mime_type, encoding = mimetypes.guess_type("Deploying a Django Application to Google App Engine.pdf")
print("MIME Type of PDF File : {}".format(mime_type))
with open("Deploying a Django Application to Google App Engine.pdf", "rb") as fp:
pdf_data = fp.read()
message.add_attachment(pdf_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="gcloud.pdf")
############ Zip File ######################
mime_type, encoding = mimetypes.guess_type("docs.zip")
print("MIME Type of ZIP File : {}".format(mime_type))
with open("docs.zip", "rb") as fp:
image_data = fp.read()
message.add_attachment(image_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="docs.zip")
########################## Content Type #################
print("\nContent Type : {}".format(message.get_content_type()))
print("Is Multipart? : {}".format(message.is_multipart()))
print("Content Disposition : {}".format(message.get_content_disposition()))
################# Message Parts #####################
print("\n================ Message Parts ===================")
for part in message.iter_parts():
print("\nAttachment Type : {}".format(type(part)))
print("Content Type : {}".format(part.get_content_type()))
print("Is Multipart? : {}".format(part.is_multipart()))
print("Is Attachment? : {}".format(part.is_attachment()))
print("Content Disposition : {}".format(part.get_content_disposition()))
As a part of our ninth example, we'll explain how we can access all parts of the message using walk() method of EmailMessage instance.
Our code for this example is almost the same as our code for the previous two examples. We are looping through message parts using walk() method at last and printing details of the message like content type, disposition, etc. We can notice from the output that this method also returns a message with content type multipart/mixed along with attachments and main body part (text/plain).
import mimetypes
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
############# Add Attachments #############################
######### JPEG File ##################
mime_type, encoding = mimetypes.guess_type("dr_apj_kalam.jpeg")
print("MIME Type of JPEG File : {}".format(mime_type))
with open("dr_apj_kalam.jpeg", "rb") as fp:
image_data = fp.read()
message.add_attachment(image_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="kalam.jpeg")
############ PDF File ######################
mime_type, encoding = mimetypes.guess_type("Deploying a Django Application to Google App Engine.pdf")
print("MIME Type of PDF File : {}".format(mime_type))
with open("Deploying a Django Application to Google App Engine.pdf", "rb") as fp:
pdf_data = fp.read()
message.add_attachment(pdf_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="gcloud.pdf")
############ Zip File ######################
mime_type, encoding = mimetypes.guess_type("docs.zip")
print("MIME Type of ZIP File : {}".format(mime_type))
with open("docs.zip", "rb") as fp:
image_data = fp.read()
message.add_attachment(image_data, maintype=mime_type.split("/")[0],
subtype=mime_type.split("/")[1],
filename="docs.zip")
########################## Content Type #################
print("\nContent Type : {}".format(message.get_content_type()))
print("Is Multipart? : {}".format(message.is_multipart()))
print("Content Disposition : {}".format(message.get_content_disposition()))
################# Message Parts #####################
print("\n================ Message Parts ===================")
for part in message.walk():
print("\nAttachment Type : {}".format(type(part)))
print("Content Type : {}".format(part.get_content_type()))
print("Is Multipart? : {}".format(part.is_multipart()))
print("Is Attachment? : {}".format(part.is_attachment()))
print("Content Disposition : {}".format(part.get_content_disposition()))
As a part of our tenth example, we'll explain how we can convert a non-multipart message to a multipart message using make_mixed() method of EmailMessage instance.
Our code for this example first creates a mail and sets its main body like we have been doing for the last many examples. It then prints information about message like content type, content-disposition, and message sub-parts details. We are then calling make_mixed() method to convert non-multipart message to multipart. We are then again printing information about message like content type, content-disposition, and message sub-parts details. We can notice that mail's content type before was text/plain and it does not have sub-parts. After we called make_mixed() and converted message, now the content type has changed to multipart/mixed and mail has sub-part which is of typetext/plain. The main body part (text/plain) has been moved inside after the conversation.
import mimetypes
message = email.message.EmailMessage()
################ Set Headers ###################
message.add_header("From", "coderzcolumn07@gmail.com")
message.add_header("To", "sunny.2309@yahoo.in")
message.add_header("Cc", "coderzcolumn07@gmail.com")
message.add_header("Bcc", "mail2sunny.2309@gmail.com")
message.add_header("Subject", "Welcome to CoderzColumn")
##################### Set Main Content #####################
body = '''
Hi All,
How are you?
Regards,
CoderzColumn
'''
message.set_content(body)
print("\n============= Details Beofre Making multipart/mixed============")
print("\nContent Type : {}".format(message.get_content_type()))
print("Is Multipart? : {}".format(message.is_multipart()))
print("Content Disposition : {}".format(message.get_content_disposition()))
print("\n================ Message Parts ===================")
for part in message.walk():
print("\nAttachment Type : {}".format(type(part)))
print("Content Type : {}".format(part.get_content_type()))
print("Is Multipart? : {}".format(part.is_multipart()))
print("Is Attachment? : {}".format(part.is_attachment()))
print("Content Disposition : {}".format(part.get_content_disposition()))
message.make_mixed() ### Make Message multipart/mixed
print("\n============= Details After Making multipart/mixed============")
########################## Content Type #################
print("\nContent Type : {}".format(message.get_content_type()))
print("Is Multipart? : {}".format(message.is_multipart()))
print("Content Disposition : {}".format(message.get_content_disposition()))
################# Message Parts #####################
print("\n================ Message Parts ===================")
for part in message.walk():
print("\nAttachment Type : {}".format(type(part)))
print("Content Type : {}".format(part.get_content_type()))
print("Is Multipart? : {}".format(part.is_multipart()))
print("Is Attachment? : {}".format(part.is_attachment()))
print("Content Disposition : {}".format(part.get_content_disposition()))
As a part of our eleventh example, we are demonstrating how we can send mail using Python. The mail that is represented by EmailMessage instance.
Our code for this example creates a mail the same way as our previous examples with three attachments. It then sends mail using send_message() method of SMTP_SSL instance available from smtplib module of Python.
Please make a NOTE that we have not covered the working of smtplib module as a part of this tutorial. We have a different tutorial for the same. If you are interested in learning about the same then please feel free to check it.
import smtplib
import time
import email
################# SMTP SSL ################################
with smtplib.SMTP_SSL(host="smtp.gmail.com", port=465) as smtp_ssl:
print("Connection Object : {}".format(smtp_ssl))
######### Log In to mail account ############################
print("\nLogging In.....")
resp_code, response = smtp_ssl.login(user="mail2sunny.2309@gmail.com", password="app_password")
print("Response Code : {}".format(resp_code))
print("Response : {}".format(response.decode()))
################ Send Mail ########################
print("\nSending Mail..........")
message = email.message.EmailMessage()
message["From"] = "mail2sunny.2309@gmail.com"
message["To"] = ["coderzcolumn07@gmail.com", ]
message["cc"] = ["mail2sunny.2309@gmail.com",]
message["Bcc"] = ["sunny.2309@yahoo.in", ]
message["Subject"] = "Mail with attachments"
body = '''
Hello All,
Please find attached file.
Regards,
CoderzColumn
'''
message.set_content(body)
### Attach JPEG Image.
with open("dr_apj_kalam.jpeg", mode="rb") as fp:
img_content = fp.read()
message.add_attachment(img_content, maintype="image", subtype="jpeg", filename="kalam.jpeg")
### Attach PDF Image.
with open("Deploying a Django Application to Google App Engine.pdf", mode="rb") as fp:
pdf_content = fp.read()
message.add_attachment(pdf_content, maintype="application", subtype="pdf", filename="doc.pdf")
### Attach Zip Image.
with open("docs.zip", mode="rb") as fp:
zip_content = fp.read()
message.add_attachment(zip_content, maintype="application", subtype="zip", filename="docs.zip")
### Send Message
response = smtp_ssl.send_message(msg=message)
print("List of Failed Recipients : {}".format(response))
As a part of our twelfth example, we are demonstrating how we can read a mail using Python. We'll be reading the mail which we sent in our previous example and print details of the mail which we have explained in our previous examples.
Our code for this example reads the latest email from Gmail INBOX which is the mail that we sent in our last example using IMAP4_SSL instance of imaplib library. We have then used from_bytes() method of email module to transfer mail from bytes format to object of type Message which represents the mail in Python. The Message instance is almost the same as EmailMessage instance with the only change that it does not have some methods available with EmailMessage and it was part of Legacy API of email module which is still maintained.
Please make a NOTE that we have not covered the working of imaplib module as a part of this tutorial. We have a different tutorial for the same. If you are interested in learning about the same then please feel free to check it.
import imaplib
import email
################ IMAP SSL ##############################
with imaplib.IMAP4_SSL(host="imap.gmail.com", port=imaplib.IMAP4_SSL_PORT) as imap_ssl:
print("Connection Object : {}".format(imap_ssl))
############### Login to Mailbox ######################
print("Logging into mailbox...")
resp_code, response = imap_ssl.login("mail2sunny.2309@gmail.com", "app_password")
print("Response Code : {}".format(resp_code))
print("Response : {}\n".format(response[0].decode()))
############### Set Mailbox #############
resp_code, mail_count = imap_ssl.select(mailbox="INBOX", readonly=True)
############### Retrieve Mail IDs for given Directory #############
resp_code, mails = imap_ssl.search(None, "ALL")
############### Display Few Messages for given Directory #############
mail_id = mails[0].decode().split()[-1]
print("================== Start of Mail [{}] ====================\n".format(mail_id))
resp_code, mail_data = imap_ssl.fetch(mail_id, '(RFC822)') ## Fetch mail data.
message = email.message_from_bytes(mail_data[0][1]) ## Construct Message from mail data
print("From : {}".format(message.get("From")))
print("To : {}".format(message.get("To")))
print("Cc : {}".format(message.get("Cc")))
print("Bcc : {}".format(message.get("Bcc")))
print("Date : {}".format(message.get("Date")))
print("Subject : {}".format(message.get("Subject")))
print("Body : ")
for part in message.walk():
if part.get_content_type() == "text/plain":
body_lines = part.as_string().split("\n")
print("\n".join(body_lines[:12])) ### Print first 12 lines of message
print("\n\t============= Attachments ===================")
for attachment in message.walk():
content_type = attachment.get_content_type()
if not (content_type.startswith("text") or content_type.startswith("multi")):
print("\n\tAttachment Type : {}".format(attachment.get_content_disposition()))
print("\tFile Name : {}".format(attachment.get_filename()))
print("\tContent Type : {}".format(attachment.get_content_type()))
print("\n================== End of Mail [{}] ====================\n".format(mail_id))
############# Close Selected Mailbox #######################
print("\nClosing selected mailbox....")
imap_ssl.close()
This ends our small tutorial explaining how we can represent mail in Python using email module. We explained how we can create a mail with different headers and different content types.
If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.
When going through coding examples, it's quite common to have doubts and errors.
If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.
You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.
If you want to