# smtpdirectsend.py -- use pydns and smtplib to send email directly without queuing # by Tony Nelson 06 Oct 2013 # 10 Jul 2016 # Derived from 11.12.2 SMTP Example, Python Library Reference Release 2.4.3. # Modified for Direct Send, without queuing via a local SMTP server. # On a web site, useful to validate an email address, but AOL fails (again), # so only warn the user. For greylisting, on failures keep the exact same # message (and message-id:) unless the user changes the email address. import smtplib def prompt(prompt): return raw_input(prompt).strip() fromaddr = prompt("From: ") to_addr = prompt("To: ").split()[0] #DirectSend only one To: addr print "Enter message, end with ^D (Unix) or ^Z (Windows):" # Add the From: and To: header fields at the start! msg = ("From: %s\r\nTo: %s\r\n" % (fromaddr, to_addr)) #DirectSend added: from email.Utils import make_msgid msg += ( "Message-ID: %s\r\nSubject: Direct Send Test\r\n\r\n" % make_msgid() ) while 1: try: line = raw_input() except EOFError: break if not line: break msg = msg + line print "Message length is " + repr(len(msg)) #DirectSend added: import DNS # http://pydns.sourceforge.net DNS.DiscoverNameServers() to_domain = (to_addr+'@').split('@')[1] if not to_domain: raise ValueError, '''Invalid email address "%s"''' % to_addr mx = ( DNS.mxlookup(to_domain) # get sorted MX records, or [(None,to_domain)] # fall back to A record, )[0][1] # choose first (best) mx req = DNS.DnsRequest(mx, qtype='A') # must exist ("helpful" sendmail) resp = req.req() if not len(resp.answers): raise ValueError, '''Domain "%s" not found''' % to_domain print '''Sending to domain "%s"''' % mx server = smtplib.SMTP(mx) #DirectSend was 'localhost' #server.set_debuglevel(1) server.sendmail(fromaddr, [to_addr], msg) server.quit()