smtpdirectsend

Send email directly, without queuing, so a bad address can be reported to the user.

Download

View smtpdirectsend.py source

pydns from SourceForge

View the original Python smtplib example.

Google Docs slideshow.

Description

When a user enters an email address on a web site, and a welcome email would be sent, sending the email immediately allows notifying the user if the address does not work -- except that emails are usually queued and always succeed. Sending the email directly to the recipient's mailserver, using Python's smtplib library and the pydns library on SourceForge, allows getting and reporting any errors.

Installation

Download smtpdirectsend.py and pydns into the same directory.

Usage

[tonynelson@linode ~]$ python smtpdirectsend.py 
From: obscured@georgeanelson.com
To: obscured@comcast.net
Enter message, end with ^D (Unix) or ^Z (Windows):
test smtpdirectsend
Message length is 184
Sending to domain "mx1.comcast.net"
[tonynelson@linode ~]$

The Code

import smtplib

def prompt(prompt):
    return raw_input(prompt).strip()

fromaddr = prompt("From: ")
to_addr = prompt("To: ").split()[0]
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))from email.Utils import make_msgid
msg += ( "Message-ID: %s\r\nSubject: Direct Send Test\r\n\r\n"
       % make_msgid() ) # greylisting: keep same id unless addr changes
while 1:
    try:
        line = raw_input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print "Message length is " + repr(len(msg))

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)server.sendmail(fromaddr, [to_addr], msg)
server.quit()

 

Back to Tony NelsonJHC's R Pentomino's Home Page

Valid HTML 4.0! Valid CSS!