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


View source

pydns from SourceForge

View the original Python smtplib example.

Google Docs slideshow.


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.


Download and pydns into the same directory.


[tonynelson@linode ~]$ python 
Enter message, end with ^D (Unix) or ^Z (Windows):
test smtpdirectsend
Message length is 184
Sending to domain ""
[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:
        line = raw_input()
    except EOFError:
    if not line:
    msg = msg + line

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

import DNS                                  #
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)


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

Valid HTML 4.0! Valid CSS!