📤 Sending an email attachment using Python

Software Engineering 2542 views

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:

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 = 'example@example.com'  # shared mailbox address
message_to = 'example@example.com'  # 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())

part.add_header('Content-Disposition', 'attachment; filename="%s"' % (attachment_file_name))


server = smtplib.SMTP('host.example.com')
server.sendmail(message_from, message_to, message.as_string())

Change example@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 [1]: import mimetypes In [2]: mimetypes.guess_type('example.pdf')[0] Out[2]: 'application/pdf'

Common Mimetypes

Here's a list of common mimetimes I support in my web applications:

Ext Mimetype
.csv text/plain
.tsv text/tab-separated-values
.sql text/x-sql
.xls application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.gz application/x-gzip
.gzip application/x-gzip
.zip application/zip

Check out Media Types on IANA for the official list.