|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +"""Send email blasts to lists of addresses |
| 4 | +
|
| 5 | +Sample use: |
| 6 | + ./mailtool.py --body=samplebody.txt --tolist=samplerecipients.txt \ |
| 7 | + --subject="Testing 123" |
| 8 | +""" |
| 9 | + |
| 10 | +import datetime |
| 11 | +import gflags |
| 12 | +import smtplib |
| 13 | +import sys |
| 14 | + |
| 15 | + |
| 16 | +gflags.DEFINE_string('body', '', 'Body of email') |
| 17 | +gflags.DEFINE_string('tolist', '', |
| 18 | + 'List of addresses to send to. One per line') |
| 19 | +gflags.DEFINE_string('mailserver', 'localhost', 'Mail server to send to') |
| 20 | +gflags. DEFINE_string( 'mailfrom', '[email protected]', |
| 21 | + 'Address to use as from address') |
| 22 | +gflags.DEFINE_string('subject', '', 'Subject for the email') |
| 23 | +FLAGS = gflags.FLAGS |
| 24 | + |
| 25 | + |
| 26 | +def SendEmail(to, subject, body): |
| 27 | + s = smtplib.SMTP(FLAGS.mailserver) |
| 28 | + s.sendmail(FLAGS.mailfrom, [to], |
| 29 | + """From: %(from)s\r |
| 30 | +To: %(to)s\r |
| 31 | +Subject: %(subject)s\r |
| 32 | +\r |
| 33 | +%(body)s""" % {'from': FLAGS.mailfrom, |
| 34 | + 'to': to, |
| 35 | + 'subject': subject, |
| 36 | + 'body': body}) |
| 37 | + s.quit() |
| 38 | + |
| 39 | + |
| 40 | +def main(argv): |
| 41 | + # Parse flags |
| 42 | + try: |
| 43 | + argv = FLAGS(argv) |
| 44 | + |
| 45 | + except gflags.FlagsError, e: |
| 46 | + print 'Flags error: %s' % e |
| 47 | + print |
| 48 | + print FLAGS |
| 49 | + |
| 50 | + if len(FLAGS.subject) == 0: |
| 51 | + print 'Set a subject!' |
| 52 | + sys.exit(1) |
| 53 | + if len(FLAGS.tolist) == 0: |
| 54 | + print 'Set a list of recipients!' |
| 55 | + sys.exit(1) |
| 56 | + if len(FLAGS.body) == 0: |
| 57 | + print 'Set an email body!' |
| 58 | + sys.exit(1) |
| 59 | + |
| 60 | + f = open(FLAGS.body, 'r') |
| 61 | + body = f.read() |
| 62 | + f.close() |
| 63 | + |
| 64 | + f = open(FLAGS.tolist, 'r') |
| 65 | + addresses = f.readlines() |
| 66 | + f.close() |
| 67 | + |
| 68 | + count = 0 |
| 69 | + for address in addresses: |
| 70 | + address = address.rstrip() |
| 71 | + SendEmail(address, FLAGS.subject, body) |
| 72 | + count += 1 |
| 73 | + print '%s: %d of %d sent' %(datetime.datetime.now(), |
| 74 | + count, len(addresses)) |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == "__main__": |
| 78 | + main(sys.argv) |
0 commit comments