Python by Example

Mailing List Utility



import sys
import string
import rfc822
import smtplib


Note the use of modules to package related functions and classes, similar to Delphi's units.

def usage():

    print "Usage:  newsletter [-t] body-file [addr-file]"
    sys.exit( 1 )

def main():

    if( len( sys.argv ) < 2 or len( sys.argv ) > 4 ):
        usage()

    args = sys.argv[:]

    doSendMail = 1

    if( args[ 1 ] == "-t" ):
        args = args[ 1:]
        doSendMail = 0

    msgfile = args[ 1 ]

    if( len( args ) < 3 ):
        addrfile = "HADPemail.txt"

    else:
        addrfile = args[ 2 ]

Arrays and lists are first-class citizens in Python, and have powerful built-in operations (note the "slicing" of the argv array).

    mf = open( msgfile, 'r' )
    af = open( addrfile, 'r' )

    if( not mf or not af ):
        usage()

    fromaddr = "Tres Seaver "
    CRLF     = "\r\n"

    toaddrs = []
    toaddrs.append( fromaddr  )

    for line in af.readlines():
        toaddrs.append( '<' + line[:-1] + '>' )


Build up a list from the address file. Note the "clean" syntax:
  • Indentation replaces "noise" words / symbols, leaving "executable pseudo-code."
  • Variables are always declared by being defined, increasing their cognitive "locality of reference."


    msg = 'From: ' + fromaddr + CRLF
    msg = msg + 'To: "HADP members"' + CRLF
    msg = msg + 'Subject: HADP Meeting announcment' + CRLF + CRLF

    for line in mf.readlines():
        msg = msg + line[:-1] + CRLF

    print "Message length:      "   + `len( msg )`
    print "Number of addresses: "   + `len( toaddrs )`


Read the body of the message.

    if( doSendMail ):
        server = smtplib.SMTP( 'smtp.neosoft.com' )
        server.set_debuglevel(1)
        server.sendmail( fromaddr, toaddrs, msg )
        server.quit()
    else :
        print "Testing: "
        print fromaddr
        for addr in toaddrs: print addr
        print
        print msg

if __name__ == '__main__':
    main()


VOILA! As one speaker at the recent International Python Conference noted, "Python comes with batteries included" (I didn't have to write the SMTP code!).
[ Top | Links ]
Copyright 1999, Tres Seaver. All rights reserved.