python-dev – Moy Blog https://moythreads.com/wordpress Abandon All Hope, Ye Who Read This Blog Mon, 15 Feb 2021 22:51:26 +0000 en-US hourly 1 https://wordpress.org/?v=5.1.9 Sending email with python without an MTA https://moythreads.com/wordpress/2015/07/09/sending-email-with-python-without-an-mta/ https://moythreads.com/wordpress/2015/07/09/sending-email-with-python-without-an-mta/#comments Thu, 09 Jul 2015 21:21:50 +0000 http://www.moythreads.com/wordpress/?p=280 Continue reading ]]> I always found puzzling that to send simple notification emails all examples I could find on the web required a valid account on an MTA and hard-coding your credentials in the script or some other dependencies that seemed a bit non-straight forward to me.

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.

]]>
https://moythreads.com/wordpress/2015/07/09/sending-email-with-python-without-an-mta/feed/ 4