CSC111 sendMail.py

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 12:30, 12 April 2010 (UTC)


""" 
sendMail.py
D. Thiebaut
Example program for sending email from within python code.
"""
import os

#--------------------------------------------------------
# Mail message format.  Do not change!
#--------------------------------------------------------
MESSAGE = """To: %s
From: %s
Subject: %s

%s
"""  

#--------------------------------------------------------
# sendmail
#--------------------------------------------------------
def sendmail( recipient, sender, subject, body ):
    """sends the body string to the recipient, specifying the sender and
    the subject of the message.  The program specified in MAIL is used
    as the mailer program"""


    #--- create message ---
    msg = MESSAGE % ( recipient, sender, subject, body )

    #--- open a pipe to the mailer and send it the text of the message ---
    p = os.popen("/usr/sbin/sendmail -t", 'w')
    p.write( msg ) 
    exitcode = p.close()

    #--- if the mailer closed with an error, report it ---
    if exitcode:
        print "Exit code: %s" % exitcode



#--------------------------------------------------------
# main
#--------------------------------------------------------
def main():
    sendmail( "111c@beowulf.csc.smith.edu", "thiebaut@cs.smith.edu", 
              "No class on Friday!", 
              "Hello\nThere won't be class on Friday!\n\nEnjoy!" )
    

main()