1000 Python Questions
Get 1 Python question daily. Join this telegram channel https://t.me/python1000questions
Advertise with us
Sending email with attachments using Python built-in email module

The email built-in Python module lets us easily construct email messages.

We'll start by using the email.message.EmailMessage class to create an email message.

>>> from email.message import EmailMessage
>>> message = EmailMessage()
>>> sender = "me@example.com"
>>> recipient = "you@example.com" >>> message['From'] = sender
>>> message['To'] = recipient
>>> message['Subject'] = 'Greetings from {} to {}!'.format(sender, recipient)
>>> print(message)

Printing the message object gives us the string representation of that object


From: me@example.com
To: you@example.com
Subject: Greetings from me@example.com to you@example.com!

FromTo, and Subject are examples of email header fields. They’re key-value pairs of labels and instructions used by email clients and servers to route and display the email. They’re separate from the email's message body, which is the main content of the message.

Adding a body:

>>> body = """Hey there!. I'm learning to send emails using Python!"""
>>> message.set_content(body)
>>> print(message)

From: me@example.com
To: you@example.com
Subject: Greetings from me@example.com to you@example.com!
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hey there! I'm learning to send email using Python!

The set_content() method automatically added a couple of headers that the email infrastructure will use when sending this message to another machine. The Content-Type and Content-Transfer-Encoding headers tell email clients and servers how to interpret the bytes in this email message into a string. 

Adding an attachment:

Email messages are made up completely of strings. When you add an attachment to an email, whatever type the attachment happens to be, it’s encoded as some form of text. The Multipurpose Internet Mail Extensions (MIME) standard is used to encode all sorts of files as text strings that can be sent via email.

In order for the recipient of your message to understand what to do with an attachment, we need to label the attachment with a MIME type and subtype to tell them what sort of file you’re sending. The Internet Assigned Numbers Authority (IANA) (iana.orghosts a registry of valid MIME types. If you know the correct type and subtype of the files you’ll be sending, you can use those values directly. If you don't know, you can use the Python mimetypes module to make a good guess.

>>> attachment_path = "/tmp/image.png"
>>> attachment_filename = os.path.basename(attachment_path)
>>> import mimetypes
>>> mime_type, _ = mimetypes.guess_type(attachment_path)
>>> print(mime_type)

mime_type string contains the MIME type and subtype, separated by a slash. The EmailMessage type needs a MIME type and subtypes as separate strings.

>>> mime_type, mime_subtype = mime_type.split('/', 1)
>>> print(mime_type)
>>> print(mime_subtype)

Now add the attachment to mail and print it.

>>> with open(attachment_path, 'rb') as ap:
... message.add_attachment(ap.read(), maintype=mime_type, subtype=mime_subtype,
... filename=os.path.basename(attachment_path))
>>> print(message)


Content-Type: multipart/mixed; boundary="===============5350123048127315795=="
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hey there! I'm learning to send email using Python!
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="image.png"
MIME-Version: 1.0
(... few lines deleted ...)

The entire message can be serialized as a text string, including the image that we attached. The email message as a whole has the MIME type "multipart/mixed". Each part of the message has its own MIME type. The message body is still there as a "text/plain" part, and the image attachment is an "image/png" part.

Sending mail:

To send emails, our computers use the Simple Mail Transfer Protocol (SMTP). This protocol specifies how computers can deliver emails to each other. There are certain steps that need to be followed to do this correctly. But we won't do this manually. We’ll send the message using the built-in smtplib Python module.

>>> import smtplib
>>> mail_server = smtplib.SMTP_SSL('smtp.example.com')
>>> sender = "from-address@example.com" >>> password = "**********"
>>> mail_server.login(sender, password)
>>> mail_server.send_message(message)
>>> mail_server.quit()

Host your Django Application for free on PythonAnyWhere. If you want full control of your application and server, you should consider DigitalOcean. Create an account with this link and get $100 credits.

Related Articles:
Adding Email Subscription Feature in Django Application
email subscription feature in django, sending email subscription confirmation mail in django, sending email unsubscribe email in Django, Add subscription feature in Django...
How to Track Email Opens Sent From Django App
How to track email opens. Tracking email sent from django app. Finding the email open rate in Python Django. Email behaviour of users in Python Django. Finding when email is opened by user in python-django....
Sending Emails Using Python and Gmail
Python code to send free emails using Gmail credentials, Sending automated emails using python and Gmail, Using Google SMTP server to send emails using python. Python script to automate gmail sending emails, automating email sending using gmail...
Python Script 2 : Crawling all emails from a website
Website crawling for email address, web scraping for emails, data scraping and fetching email adress, python code to scrape all emails froma websites, automating the email id scraping using python script, collect emails using python script...
Please subscribe to get the latest articles in your mailbox.

© 2017-2020 Python Circle   Contact   Sponsor   Archive   Sitemap