Sending emails from Python through a Gmail account

danielhomola Blog Leave a Comment

In my current research I’m building a new research tool for the integration and visualisation of genomic data. The application starts with a file-upload form, then runs a pretty complex pipeline on our server and cluster that can take hours to complete. So once it’s finished I need to notify the users about any errors, warnings, send them the result files and a link to the visualisation. Also I’d like to know how each run went, regardless where am I, so it has to send a copy of the run’s log file to my email address.

As usual Python has an amazing in-built library for dealing with emails which can do pretty much whatever the hell you want. But it still takes a couple lines of code to send an email, so I wrote a tiny class to take care of it. It can send emails to multiple recipients and attach any kind of document, file or image, all it needs is a Gmail account. It also accepts HTML formatted messages as input, so you can send some pretty nice looking things with it (but if you prefer simple text, just use that instead). Even better you can tweak the code super easily to use any smtp server instead of Gmail’s.

Here is the source code on my Bitbucket. Or just run:

And here is a short example.

Let me know if you have suggestions or if you’ve noticed a bug. Cheers!

danielhomolaSending emails from Python through a Gmail account