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.

Edward J. Stembler is a Software Engineer with 21+ years experience in designing and creating software solutions across a wide range of technologies. Passionate about Machine Learning, Data Science, Data Visualization, Elixir, Ruby, Python, Raspberry Pi, Arduino, and Robotics.

Leave a reply:

Your email address will not be published.

Sliding Sidebar

Tweets

Instagram

  • Loved the Croquetas De Jamon Catracho and Toffee Pudding! Alexhellip
    4 weeks ago by ejstembler Loved the Croquetas De Jamon, Catracho, and Toffee Pudding! Alex loved the medium-rare Catracho tenderloin too! And Yana loved the grilled octopus with sour cabbage slaw. We met the chef afterwards. She brought us these tiny Alfajores cookies. Alex asked her what is was, she told him he'd like it. He licked a cookie suspiciously and told her, "There's something wrong with this chocolate. It's too sweet!"
  • 5 burger night!
    1 month ago by ejstembler $5 burger night!
  • Slowly finishing off a loaf of Chicago Italian bread Yesterdayhellip
    1 month ago by ejstembler Slowly finishing off a loaf of Chicago Italian bread. Yesterday it was an egg sandwich, today French toast
  • Chicken Cacciatore for dinner!
    1 month ago by ejstembler Chicken Cacciatore for dinner!
  • Bangers amp Mash amp Newcastle for dinner
    1 month ago by ejstembler Bangers & Mash & Newcastle for dinner