sending emails using python

Brendon Towle Brendon at BrendonTowle.com
Thu Sep 7 07:17:18 EDT 2006


On Sep 7, 2006, at 3:50 AM, "sridhar"  
<ramasridhar.kasturi at gmail.com>wrote:


> iam having user account on an exchangeserver.
> with that can i send an email using python?
>
> if iam using the following code iam getting error
>
>
> fromAddress = 'sridhar_kasturi at satyam.com'
> toAddress = 'sridhar_kasturi at satyam.com'
> msg = "Subject: Hello\n\nThis is the body of the message."
> import smtplib
> server = smtplib.SMTP("hstmsg002",25)
> server.sendmail(fromAddress, toAddress, msg)
>
> error:
>
> Traceback (most recent call last):
>   File
> "C:\sridhar\Beginning_Python\Beginning_Python\Chapter16\tryitout 
> \InitialMailExample.py",
> line 5, in ?
>     server = smtplib.SMTP("hstmsg002",25)
>   File "C:\Python24\lib\smtplib.py", line 244, in __init__
>     (code, msg) = self.connect(host, port)
>   File "C:\Python24\lib\smtplib.py", line 307, in connect
>     (code, msg) = self.getreply()
>   File "C:\Python24\lib\smtplib.py", line 351, in getreply
>     raise SMTPServerDisconnected("Connection unexpectedly closed")
> SMTPServerDisconnected: Connection unexpectedly closed
>

I saw a similar error when I was not following the server's  
authentication protocol -- either failing to authenticate when it  
wanted it, or authenticating when it didn't want it. Here's the code  
I use -- tested on both an Exchange server and on Comcast's SMTP  
servers. It assumes some globals (in all caps) which you need to set  
first.

def emailGivenString(host=SMTP_HOST, fromAddr=FROM_ADDR,
                      toAddr=TO_ADDR, subject='', body='', auth=False):
     server = smtplib.SMTP(host)
     if auth:
         server.login('username', 'password')
     outMessage = 'From: %s\rTo: %s\rSubject: %s\r%s' %
                  (FROM_HEADER, TO_HEADER, subject, body)
     server.sendmail(fromAddr, toAddr, outMessage)

If this doesn't work, I second the previous suggestion of talking to  
the server admin.

B.

--
Brendon Towle, Ph.D.   <Brendon at BrendonTowle.com>  +1-412-362-1530
“Debugging is twice as hard as writing the code in the first place.  
Therefore,
if you write the code as cleverly as possible, you are, by  
definition, not
smart enough to debug it.” – Brian W. Kernighan





More information about the Python-list mailing list