How to Send Email With Attachment Using Python

In this tutorial we will explore how to send email with attachment using Python’s multiple inbuilt libraries and Gmail SMTP connection. There might be requirement of sending some type of file with your email, be it a excel file or pdf or even a audio or image file also. This is the method will help you to achieve the same.

Here is a step by step explanation of how to send an HTML email with attachment. At the end of the post full code is available.

In the first two part of this post we have explained :

Some Important Points About Attachment

  1. If you have gone through how to send HTML email with Python, you will see there we are using MIME objects for constructing the email. For that we are using MIMEText and MIMEMultipart. Attachments are still the MIME objects, but we need to encode them with the base64 module that encodes all binary data into ASCII characters.
  2. Python let you attach various type of files like .txt, image, audio, video, app, excel, pdf and many more. For that you just need to use appropriate email class like email.mime.audio.MIMEAudio or email.mime.image.MIMEImage etc.
  3. For more information on this you can refer to this Python documentation or you can check these example provided.
  4. File size more that 20MB is a bad practice.

In this post we will see how to send a pdf file in our mail. You can attach even a .txt file also.

Steps to Send Email With Attachment

Step1: First import the required modules/class.

import smtplib

# Import corresponding modules
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

Step2: Next add the Gmail smtp connection details.

# Gmail SMTP configuration
smtp_server = 'smtp.gmail.com'
smtp_port = 587
sender_email = 'sender_email_address'
sender_password = 'Gmail App Password'  #You have to use the Google app password here
receiver_email = 'receiver_email_address'

Step3: Create the Multipart message object and add the required values.

# Create a multipart message
message = MIMEMultipart('alternative')
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'Email with Attachment'

Step4: Add the body of the email. We will add both plain text version and HTML version of the mail body. Incase the email client not able to render the HTML version then the plain version will be shown.

# write the text/plain version of the email
text = """\
Hi,
Check out the new blog post on the Python Addict: "Send Email Using Python: 
at https://pythonaddict.com/python/sending-emails-with-python/. 
Let us know what content would be useful for you!"""

# write the HTML version of the email
html = """\
<html>
  <body>
    <p>Hi,<br>
       Check out the new blog post on the Python Addict: "Send Email Using Python:</p>
    <p><a href="https://pythonaddict.com/python/sending-emails-with-python/">Send Email Using Python</a></p>
    <p> Feel free to <strong>let us know</strong> What else we can add for you!</p>
  </body>
</html>
"""

part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)

Step5: Add the attachment to our email body.

# Attachment The File
attachment_path = 'mention the full path to your attachment file'

with open(attachment_path, 'rb') as attachment_file:
    # The content type "application/octet-stream" means that a MIME attachment is a binary file
    part = MIMEBase('application', 'octet-stream')      
    part.set_payload(attachment_file.read())

# Encode to base64
encoders.encode_base64(part)

# Add header 
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {'mention your file name here'}",
)

# Add attachment to your message
message.attach(part)

Step6: Now create the secure connection and send mail using the send_message() function.

# Create a secure connection and send the email
with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender_email, sender_password)
    server.send_message(message)

print('Email sent successfully.')

Here is the full code to send an email with attachment using Python.

import smtplib

# Import corresponding modules
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders


# Gmail SMTP configuration
smtp_server = 'smtp.gmail.com'
smtp_port = 587
sender_email = 'sender_email_address'
sender_password = 'Gmail App Password' #You have to use the Google app password here. https://pythonaddict.com/utility/how-to-generate-google-application-password/
receiver_email = 'receiver_email_address'


# Create a multipart message
message = MIMEMultipart('alternative')
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'Email with Attachment'

# write the text/plain version of the email
text = """\
Hi,
Check out the new blog post on the Python Addict: "Send Email Using Python: 
at https://pythonaddict.com/python/sending-emails-with-python/. 
Let us know what content would be useful for you!"""

# write the HTML version of the email
html = """\
<html>
  <body>
    <p>Hi,<br>
       Check out the new blog post on the Python Addict: "Send Email Using Python:</p>
    <p><a href="https://pythonaddict.com/python/sending-emails-with-python/">Send Email Using Python</a></p>
    <p> Feel free to <strong>let us know</strong> What else we can add for you!</p>
  </body>
</html>
"""

part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)

# Attachment The File
attachment_path = 'mention the full path to your attachment file' # Use a pdf file or txt file for testing.


with open(attachment_path, 'rb') as attachment_file:
    # The content type "application/octet-stream" means that a MIME attachment is a binary file
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(attachment_file.read())

# Encode to base64
encoders.encode_base64(part)

# Add header
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {'mention your file name here'}",
)

# Add attachment to your message
message.attach(part)

# Create a secure connection and send the email
with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender_email, sender_password)
    server.send_message(message)

print('Email sent successfully.')

Conclusion

In this post we explored how to send emails with attachment using Python the easiest way. You can in your application to send various emails with attachment to your users. If you face any issue please comment below.

You may like how to send plain email using Python and how to send HTML email using Python.

Leave a Reply

Scroll to Top