Home > python > email notification from a script

email notification from a script

Problem
You want to send an email to yourself from a script.

Solution
You can find here how to do it from a Bash script. That solution uses the mailx command.

Here is a simple Python wrapper for the mailx command:

#!/usr/bin/env python3
# coding: utf8

import os

DEBUG = True
# DEBUG = False

class NoSubjectError(Exception):
    pass

class NoRecipientError(Exception):
    pass

def send_email(to='', subject='', body=''):
    if not subject:
        raise NoSubjectError
    if not to:
        raise NoRecipientError
    #
    if not body:
        cmd = """mailx -s "{s}" < /dev/null "{to}" 2>/dev/null""".format(
            s=subject, to=to
        )
    else:
        cmd = """echo "{b}" | mailx -s "{s}" "{to}" 2>/dev/null""".format(
            b=body, s=subject, to=to
        )
    if DEBUG:
        print("#", cmd)
    #
    os.system(cmd)

def main():
    send_email(to="to@email.com",
               subject="subject")
    #
    send_email(to="to@email.com",
               subject="subject",
               body='this is the body of the email')

#############################################################################

if __name__ == "__main__":
    main()

You can also find this code as a gist.

Categories: python Tags: , ,
  1. June 17, 2016 at 21:26

    The first time I had this problem, I used a php script to do this. Dropped that and moved to using mutt directly from my bash scripts.

    This looks like an interesting alternative as well.

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: