Categories
Python Answers

How to send email attachments with Python?

Spread the love

Sometimes, we want to send email attachments with Python.

In this article, we’ll look at how to send email attachments with Python.

How to send email attachments with Python?

To send email attachments with Python, we can use the smtplib library.

For instance, we write

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders


SUBJECT = "Email Data"

msg = MIMEMultipart()
msg['Subject'] = SUBJECT 
msg['From'] = self.EMAIL_FROM
msg['To'] = ', '.join(self.EMAIL_TO)

part = MIMEBase('application', "octet-stream")
part.set_payload(open("text.txt", "rb").read())
Encoders.encode_base64(part)
    
part.add_header('Content-Disposition', 'attachment; filename="text.txt"')

msg.attach(part)

server = smtplib.SMTP(self.EMAIL_SERVER)
server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())

to create the attachment with the MIMEBase class.

And then we call set_payload with the file we want to attach.

Next, we encode the attachment to a base64 string with Encoders.encode_base64.

And then we add the Content-Disposition header with add_header.

And then we call msg.attach with part to attach the attachment to the message.

Then we call sendmail to send the email with the attachment.

Conclusion

To send email attachments with Python, we can use the smtplib library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *