Skip to content

Instantly share code, notes, and snippets.

@acdha
Created January 14, 2009 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acdha/46962 to your computer and use it in GitHub Desktop.
Save acdha/46962 to your computer and use it in GitHub Desktop.
Jython example which uses JNDI to query DNS for MX hosts
sender = "Chris Adams <chris@improbable.org>"
recipients = [ "Chris Adams <chris@improbable.org>", ]
msg = "test message"
smtp = smtplib.SMTP()
# To avoid hard-coding our SMTP server list we'll query the
# MX records for yale.edu using the Java JNDI API:
from javax.naming.directory import InitialDirContext
jndi_ctx = InitialDirContext()
mx_hosts = jndi_ctx.getAttributes("dns:///example.edu", ["MX"]).get("MX")
for rec in mx_hosts.getAll():
mx_host = rec.split(' ', 2)[1]
try:
smtp.connect(mx_host)
smtp.sendmail(sender, recipients, msg)
smtp.close()
log("Alert email was sent to %s using %s" % (recipients, mx_host))
return
except smtplib.SMTPException, e:
log("ERROR: Unable to send message using SMTP server %s: %s" % (mx_host, e))
continue
log("ERROR: Unable to send alert email using any server in %s!" % mx_hosts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment