#!/usr/bin/env python ''' SendMail.py -- v.1.0 Jeff Temple February 27, 2012 Quick program for sending messages to various users. Program will be used by various root cron scripts for sending messages about identified problems. To change the people who receive email notifications, change the 'umdhep_admins' variable below. v1.1 -- updated to read email lists of users via parseUsers module ''' import sys sys.path.append("/root/cronscripts") import os import string import smtplib #smtplib for email sending. Python has an email package, but it seems not to have stabilized in syntax until at least python 2.7. For now, smtplib is sufficient, though not necessarily pretty. import base64 from optparse import OptionParser # Use parseUsers to read UserListCSV and get list of admins. If this fails, default list (under __main__, below) is used import parseUsers UserListCSV="/root/cronscripts/hepcms_Users.csv" # global variable that stores csv file of user info def SendMail(fromaddr=None, toaddrs=[], subject="No subject", msg="Test message", attachments=[], umdhep_admins=[], # by default, use blank admin list (assume admins listed in toaddrs; if SendMail is run as main, a default umd admin list is used debug=False): ''' Simple script to send mail. "attachments" keyword requires extra coding, and has not yet been implemented. See http://www.tutorialspoint.com/python/python_sending_email.htm for example of adding attachments. ''' if fromaddr==None: if (debug==True): print "Error, no 'from:' address specified!" return False if toaddrs<>list(toaddrs): print "WARNING! 'toaddrs' input does not appear to be a list! Converting to comma-separated list!" newaddrs=[] temp=string.strip(toaddrs) temp=string.split(temp,",") for t in temp: newaddrs.append(t) toaddrs=newaddrs if len(toaddrs)==0: if (debug==True): print "Error, no 'to:' addresses specified!" return False header="From: %s\n"%fromaddr header=header+"To: " for addr in toaddrs: if addr==toaddrs[-1]: header=header+"%s"%addr else: header=header+"%s,"%addr header=header+"\nReply-to: " for addr in umdhep_admins: if addr==umdhep_admins[-1]: header=header+"%s"%addr else: header=header+"%s,"%addr header=header+"\nSubject: %s\n"%subject if os.path.isfile(msg): temp=open(msg,'r').readlines() outmsg=header for t in temp: outmsg=outmsg+t else: outmsg=header+msg if debug: print "Prepared message for sending (test mode; will not send)." print "Message is:" print outmsg return True server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, outmsg) server.quit() return True if __name__=="__main__": parser=OptionParser() parser.add_option("-v","--debug", action="store_true", dest="debug", default=False, help="Show debug info") parser.add_option("-f","--from", dest="fromaddr", default=None, help="Specify who the message is from (Default is $USER@HOSTNAME") parser.add_option("-t","--to", dest="toaddrs", default=[], action="append", help="Specify who the message is to (Default is [] -- no recipients).") parser.add_option("-s","--subject", dest="subject", default="No subject", help="Specify subject line. Default is 'No subject'.") parser.add_option("-m","--message", dest="message", default="Test message", help="Specify mail message, either as a string, or as a file. Default is 'Test message'") parser.add_option("-z","--attach", dest="attachments", default=[], action="append", help="Specify file(s) to attach to message. Default is [] -- no files. This option is not yet available.") parser.add_option("-u","--umd", dest="umd", action="store_true", default=False, help="If set to True, umdhep admins cc'd on message. Default is False.") parser.add_option("-a","--all", dest="allusers", default=False, action="store_true", help="If set to True, emails all users in hepcms_Users.csv file. Default is False.") parser.add_option("-c","--csv", dest="csv", default=UserListCSV, help="Specify .csv file containing user info and email. Default is %s"%UserListCSV) parser.add_option("-g","--ageGreaterThan", dest="ageGreaterThan", default=None, type="int", help="If specified, only accounts with age greater than the given value (in days) will be emailed. Option used in associated with '--all' option only; ages of random accounts cannot be queried.") parser.add_option("-l","--ageLessThan", dest="ageLessThan", default=None, type="int", help="If specified, only accounts with age less than the given value (in days) will be emailed. Option used in associated with '--all' option only; ages of random accounts cannot be queried.") parser.add_option("-x","--experiment", dest="experiment", default=False, action="store_true", help="If set to True, emails only users in hepcms_Users.csv that are *not* listed as members of the theory group. Default is False.") (opts,args)=parser.parse_args() # Get list of admins, and their emails # Use the umdhep_admins global variable defined above as a default, but if .csv file is specified, read admins from that. if os.path.isfile(opts.csv): usermails=parseUsers.ParseUsers(opts.csv) user_admins=parseUsers.GetAdmins(usermails) csvumdhep_admins=[] for i in user_admins: csvumdhep_admins.append(usermails[i].email) if len(csvumdhep_admins)>0: umdhep_admins=csvumdhep_admins else: # SPECIFY DEFAULT ADMINS HERE! umdhep_admins = ["mtonjes@umd.edu", "chris.ferraioli@gmail.com", "jaimegomez27@gmail.com", "bcalvert10@gmail.com"] if opts.allusers==True: if os.path.isfile(opts.csv): usermails=parseUsers.ParseUsers(opts.csv) for i in usermails: if opts.ageGreaterThan != None: if usermails[i].accountAgeopts.ageLessThan: continue if usermails[i].email not in opts.toaddrs: opts.toaddrs.append(usermails[i].email) if opts.experiment==True: if os.path.isfile(opts.csv): usermails=parseUsers.ParseUsers(opts.csv) for i in usermails: if usermails[i].group=="theory": continue # ignore theory members if opts.ageGreaterThan != None: if usermails[i].accountAgeopts.ageLessThan: continue if usermails[i].email not in opts.toaddrs: opts.toaddrs.append(usermails[i].email) if opts.debug: print "Will send to the following addresses:" print opts.toaddrs # Set default sender if opts.fromaddr==None: user=os.getenv("USER") if user==None: user="root" host=os.popen("hostname",'r').readlines() if len(host)==0: host="hepcms-hn.umd.edu" else: host=string.strip(host[0]) opts.fromaddr="%s@%s"%(user, host) #print opts.fromaddr # Add umd hep admins if opts.umd==True: for a in umdhep_admins: if a not in opts.toaddrs: opts.toaddrs.append(a) result=SendMail(fromaddr=opts.fromaddr, toaddrs=opts.toaddrs, subject=opts.subject, msg=opts.message, umdhep_admins=umdhep_admins, debug=opts.debug) if (result==False): print print "Error sending message!" print "Run with (-v, --debug) option to get more details!" print elif (result==True and opts.debug==True): print "Successfully sent message!"