This is an alternative method that sends directly an email without intermediaries. First, you’ll need to install the dnspython package:
pip install dnspython
Now, this is the script that takes care of sending email:
#!/usr/bin/env python2.7
import sys
import smtplib
import dns.resolver
answers = dns.resolver.query('dest-server.com', 'MX')
if len(answers) <= 0:
sys.stderr.write('No mail servers found for destination\n')
sys.exit(1)
# Just pick the first answer
server = str(answers[0].exchange)
# Add the From: and To: headers
fromaddr = 'source-email@whatever.com'
toaddr = 'destination@dest-server.com'
body = 'some email body'
msg = "From: {}\r\nTo: {}\r\n\r\n{}".format(fromaddr, toaddr, body)
server = smtplib.SMTP(server)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddr, msg)
server.quit()
This script resolves the mail server DNS record for the given destination (you could use a parameter instead of hard-coding it if you want to make it more generic). Once it finds out the mail server it directly tries to contact the server and send the email there using the usual basic SMTP commands (ehlo, mail FROM:, rcpt TO: etc). No need for intermediaries for such simple cases
There are surely a bunch of more complicated scenarios this script does not handle, but, it fits nicely when you need to send emails to your sysadmin account from cron jobs on random servers in your infrastructure.
]]>