Python 3: Send SMTP Authenticated Email

Home / Python 3: Send SMTP Authenticated Email

Python 3: Send SMTP Authenticated Email

February 18, 2014 | Coding | No Comments

programming code

Write enough shell scripts and eventually you will have to write one that sends a email report, in fact now a day’s I find that most shell scripts I write (the scheduled ones anyway) require some kind of notification after they have run. Likewise, if you set up enough mail servers — usually one is enough — you will need a quick easy way to test SMTP.

Below is a python 3 script with smtplib and argparse, which sends a test email using smtp authentication.  It’s short, to the point, and I hope pretty self explanatory for anyone needing to send authenticated email via python.

#!/usr/bin/env python3

import smtplib
import argparse

def testmail(username, password, server, deliveryaddr):
    header = "From: %s\r\nTo: %s\r\nSubject: SMTP Test\r\n\r\nTest Successful" % (username, deliveryaddr)
        server = smtplib.SMTP(server)
        server.login(username, password)
        server.sendmail(username, deliveryaddr, header)
    except Exception as e:
        print("An Error Occurred! %s" % e)
        print("Test Successful")

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--user', required=True,
            help="Username for SMTP Login")
    parser.add_argument('-p', '--password', required=True,
            help="Password for SMTP Login")
    parser.add_argument('-s', '--server', required=True,
            help="SMTP Server url")
    parser.add_argument('-d', '--dest', required=True,
            help='Destination Email Address')

    args = parser.parse_args()

    testmail(args.user, args.password, args.server, args.dest)

Note: This post was recovered from an old, now defunct, blog.

About Author

about author


Jack of all trades. I.T. edition. Programmer, Systems Administrator, DevOps and whatever else comes up.