How to send an email with GMail in Python from Windows

∂ √ ¡ ŋ ∂ ♪ ђ avinns at gmail.com
Thu Mar 12 14:22:04 CET 2009


Hi
Can somebody help me with sending an email using Python from GMail
Here's what I tried but it fails always.

____________________________________________________________________
import smtplib
import base64

smtpserver = 'smtp.gmail.com'
AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1
smtpuser = 'user at gmail.com' # for SMTP AUTH, set SMTP username here
smtppass = '*****' # for SMTP AUTH, set SMTP password here

RECIPIENTS = ['someuser at gmail.com']
SENDER = 'someuser at gmail.com'
mssg = open('mssg.txt', 'r').read() # I am reading from this file on
the same directory

session = smtplib.SMTP(smtpserver,'465')
session.ehlo()
#session.esmtp_features["auth"] = "LOGIN PLAIN"
session.connect(smtpserver,'465')
session.ehlo()
session.starttls()
session.set_debuglevel(1)
session.helo()

if AUTHREQUIRED:
try:
session.login(smtpuser, smtppass)

except SMTPAuthenticationError, e:
# if login fails, try again using a manual plain login method
smtp.docmd("AUTH LOGIN", base64.b64encode( smtpuser ))
smtp.docmd(base64.b64encode( smtppass ), "")
smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
if smtpresult:
errstr = ""
for recip in smtpresult.keys():
errstr = """Could not delivery mail to: %s

Server said: %s
%s

%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
raise smtplib.SMTPException, errstr
____________________________________________________
This is the Stack Trace I got when I ran the above script after a very
long time(>15min)

Traceback (most recent call last):
File "C:\Python26\Mail.py", line 13, in <module>
session = smtplib.SMTP(smtpserver,'465')
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 296, in connect
(code, msg) = self.getreply()
File "C:\Python26\lib\smtplib.py", line 340, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Tool completed with exit code 1

______________________________________________________________________
Thanks
Avinash



More information about the Python-list mailing list