]> code.delx.au - monosys/blob - mail/sendmail.py
217ed8d8172f67510ac52069eb38701a182bc802
[monosys] / mail / sendmail.py
1 #!/usr/bin/env python
2
3 # Specify SMTP servers here
4 smtpServerList = (
5 (".internode.on.net", "mail.internode.on.net"),
6 (".usyd.edu.au", "mail.usyd.edu.au"),
7 (".iinet.net.au", "mail.iinet.net.au"),
8 (".netspace.net.au", "mail.netspace.net.au"),
9 (".optusnet.com.au", "mail.optusnet.com.au"),
10 )
11
12 ###DEFAULT_SERVER = None
13
14 import email, email.utils, smtplib, sys, urllib, subprocess
15
16 # Get the to addresses
17 toAddrs = sys.argv[1:]
18 try:
19 toAddrs.remove("--")
20 except ValueError:
21 pass
22 if len(toAddrs) == 0 or filter(lambda to: to.startswith("-"), toAddrs):
23 # Either no addresses, or an unknown parameter
24 print >>sys.stderr, "Usage: %s toAddr ..." % sys.argv[0]
25 sys.exit(1)
26
27 print os.environ
28 # Pick a SMTP server
29 try:
30 host = urllib.urlopen("http://suits.ug.it.usyd.edu.au/myip.php").read().strip()
31 for hostMatch, smtpServer in smtpServerList:
32 if host.endswith(hostMatch):
33 # Got the correct smtpServer
34 break
35 else:
36 raise Exception, "No match for hostname: %s" % host
37 except Exception, e:
38 if 'DEFAULT_SERVER' in dir():
39 smtpServer = DEFAULT_SERVER
40 else:
41 print >>sys.stderr, "Error! Couldn't pick an SMTP server"
42 print >>sys.stderr, e
43 sys.exit(1)
44
45 # Get the from address
46 message = sys.stdin.read()
47 fromAddr = email.message_from_string(message)["from"]
48 fromAddr = email.utils.parseaddr(fromAddr)[1]
49
50 if smtpServer is None:
51 cmdline = ['ssh', 'kagami', '/usr/sbin/sendmail']
52 cmdline.extend(toAddrs)
53 process = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
54 process.communicate(message)
55 sys.exit(process.wait())
56 else:
57 # Send the email
58 smtp = smtplib.SMTP(smtpServer)
59 smtp.sendmail(fromAddr, toAddrs, message)
60 smtp.quit()
61
62 sys.exit(1)