📤 Sending an email attachment using Python
Someone recently asked me how to send an email attachment using Python. Sending emails programmatically is something application developers often need to do.
In my web applications, the system will send an email in several scenarios:
- a user's job has completed or failed
- a user-submitted upload has validation errors or warnings
- a user emails another user from within the system
Although in the case of my web applications, sending an email is abstracted and simplified by the web application framework module (it's configuration-drive, and implemented with templates).
In Python you can do this using the smtplib:
import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Encoders attachment_file_name = 'example.xls' message_from = 'email@example.com' # shared mailbox address message_to = 'firstname.lastname@example.org' # recipient email address message = MIMEMultipart() message['Subject'] = 'Attachment Test' message['From'] = message_from message['To'] = message_to part = MIMEBase('application', 'vnd.ms-excel') part.set_payload(open(attachment_file_name, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (attachment_file_name)) message.attach(part) server = smtplib.SMTP('host.example.com') server.sendmail(message_from, message_to, message.as_string())
Change email@example.com and host.example.com to the values you require. If you'll be sending email regularly from your script or application.
If you're not sure which mimetype to use, use the default application/octet-stream for attachments. Or, you can use the mimetypes library to look it up:In :
import mimetypesIn :
Here's a list of common mimetimes I support in my web applications:
Check out Media Types on IANA for the official list.