Send an Gmail/SMS message from Python

Sometimes you'd like a server to notify you when its done with a job, with a minimal amount of configuration. Fortunately, Python's smtplib facilitates this.

The function below sends an email to from your Gmail account (as specified by user and pwd) to a recipient with an associated subject and body.

def send_email(user, pwd, recipient, subject, body):
    import smtplib
    gmail_user = user
    gmail_pwd  = pwd
    FROM       = user
    TO         = recipient if type(recipient) is list else [recipient]
    SUBJECT    = subject
    TEXT       = body

    # Prepare actual message
    message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
        server = smtplib.SMTP("", 587)
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        print 'successfully sent the mail'
        print "failed to send mail"

You can put this in a script and have it trigger like so:

send_email("","mypassword","","Job XXXX is done","Done.")

You can also use it to send SMS messages to yourself, if you know your provider's SMS gateway. For instance, I use Ting for my cell service, so I can send myself SMS messages with:

send_email("","mypassword","","","Job XXXX is done.")

Credit: We have David Okwii's SO answer to thank for this.