Sending an email attachment using Python

📤 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 (schedule/sample) has validation errors or warnings
  • a user emails another user from within the system
  • etc…

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:

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.

Leave a reply:

Your email address will not be published.

Site Footer

Sliding Sidebar