smtplib starttls gmail example - comments?

Tim Williams tim at tdw.net
Wed Jan 24 11:56:28 CET 2007


On 24/01/07, py <py at th.on> wrote:
> I would love for anybody to comment on this code with regard to redundancy/efficiency/wordiness or whatever else.
> for instance, do i understand correctly that i cant have a try: else: without an intervening except:?
> -dave
>
>         stdout.write("calling smtp server...")
>         try:
>             server = SMTP(msgsmtp)
>         except:
>             stdout.write("FAIL.")   #using .write to avoid the implied \n with print
>         else:
>             server.set_debuglevel(msgdebug)
>             stdout.write("starting tls...")
>             server.ehlo(msgfrom)
>             try:    server.starttls()
>             except: stdout.write("FAIL.")
>             else:
>                 server.ehlo(msgfrom)           #neessary duplication (?)
>                 stdout.write("logging in...")
>                 try:    server.login(msgfrom, msgpass)
>                 except: stdout.write("FAIL.")
>                 else:
>                     stdout.write("sending...")
>                     try:    server.sendmail(msgfrom, msgto, msgtxt + "\n.\n")
>                     except: stdout.write("FAIL.")
>                     else:
>                         try:
>                             server.quit()
>                         except sslerror:      # a known and largely ignored issue with early EOF in ssl protocol
>                             stdout.write("success.")
>                         else:
>                             stdout.write("success.")
> --


*** Not tested  but should have the same functionality and error
handling as your script ***

this_host = 'myhostname.mydom1.com'
print "calling smtp server...", #  the trailing comma removes '\n'
try:
    server = smtplib.SMTP(msgsmtp,local_hostname=this_host)
    server.set_debuglevel(msgdebug)
    print "starting tls...",
    server.starttls()
    server.ehlo(this_host)  # RFC requirement for 2nd EHLO after requesting TLS
    print "logging in...",
    server.login(msgfrom, msgpass)
    print "sending...",
    failed = server.sendmail(msgfrom, msgto, msgtxt + "\n.\n")
    try:
        server.quit()
    except: pass
    print "success."
except:
    print "FAIL.",

if failed:
    print "failed:", failed  # some recipients, but not all of them, failed



More information about the Python-list mailing list