views:

4486

answers:

11

I've been trying (and failing) to figure out how to send email via Python.

Trying the example from here: http://docs.python.org/library/smtplib.html#smtplib.SMTP

but added the line server = smtplib.SMTP_SSL('smtp.gmail.com', 465) after I got a bounceback about not having an SSL connection.

Now I'm getting this:

Traceback (most recent call last):
  File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
    server = smtplib.SMTP('smtp.gmail.com', 65)
  File "C:\Python26\lib\smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python26\lib\smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "C:\Python26\lib\socket.py", line 512, in create_connection
    raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>

Thoughts?

A: 

Incorrect port maybe? I'm using 587 for smtp.gmail.com and it works.

Abgan
A: 

You should check your port, I'm not sure that google's SMTP port is 65, that would explain the timeout.

Modify your sources as such:

smtplib.SMTP_SSL('smtp.google.com', 465)

If, however, you are certain that it ought to work and it doesn't, it appears that there are some problems with smtplib.SMTP_SSL, and there's an available patch for it here.

EndUsr
A: 

Well when I just have the SSL I get the error " File "C:\Python26\lib\smtplib.py", line 310, in send raise SMTPServerDisconnected('please run connect() first') SMTPServerDisconnected: please run connect() first " but the generic connect command doesn't seem to work... I'll try the patch. How do I do that? Newbie here. :)

Chatter
Not an answer. Please update your question with these additional facts.
S.Lott
A: 

I'm using a version of Python (2.6) that I downloaded two days ago... Since the patch was in November, wouldn't I have it already?

Using the line "server = smtplib.SMTP_SSL('smtp.google.com', 465)" gives me the error

"

Traceback (most recent call last):
  File "C:\Python26\08_emailconnects\12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
    server = smtplib.SMTP_SSL('smtp.google.com', 465)
  File "C:\Python26\lib\smtplib.py", line 749, in __init__
    SMTP.__init__(self, host, port, local_hostname, timeout)
  File "C:\Python26\lib\smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python26\lib\smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python26\lib\smtplib.py", line 754, in _get_socket
    self.sock = socket.create_connection((host, port), timeout)
  File "C:\Python26\lib\socket.py", line 512, in create_connection
    raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>

"

Chatter
Not an answer. Please update your question with these additional facts.
S.Lott
A: 

server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).

I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.

"

import smtplib

mailuser = '[email protected]'

mailpasswd = 'MYPASSWORD'

fromaddr = '[email protected]'

toaddrs = '[email protected]'

msg = 'Hooooorah!'

print msg

server = smtplib.SMTP_SSL('smtp.google.com')

server = smtplib.SMTP_SSL_PORT=587

server.user(mailuser)

server.pass_(mailpasswd)

server.set_debuglevel(1)

server.sendmail(fromaddr, toaddrs, msg)

server.quit()

"

and then I get this error message: "

Traceback (most recent call last):
  File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
    server = smtplib.SMTP_SSL('smtp.google.com')
  File "C:\Python26\lib\smtplib.py", line 749, in __init__
    SMTP.__init__(self, host, port, local_hostname, timeout)
  File "C:\Python26\lib\smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python26\lib\smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
    self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
  File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
    suppress_ragged_eofs=suppress_ragged_eofs)
  File "C:\Python26\lib\ssl.py", line 118, in __init__
    self.do_handshake()
  File "C:\Python26\lib\ssl.py", line 293, in do_handshake
    self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

"

note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP underscore SSL underscore PORT=587", there's some sort of formatting thing going on here.

Chatter
Not an answer. Please update your question with these additional facts.
S.Lott
+5  A: 

The following code works for me:

import smtplib

FROMADDR = "[email protected]"
LOGIN    = FROMADDR
PASSWORD = "my.real.password"
TOADDRS  = ["[email protected]"]
SUBJECT  = "Test"

msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
       % (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"

server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()

I'm using Python 2.5.2.

Edit: changed port from 25 to 587 as suggested by ΤΖΩΤΖΙΟΥ, and dropped the second ehlo(). Now I would love to know why port 25 works perfectly from my machine (and port 465 does not).

Federico Ramponi
Using Python 2.4.4 and your example I received the following error: SMTP AUTH extension not supported by server. I was able to get around it by adding a second ehlo() after the call to starttls()
Jataro
The call to server.ehlo() is unneeded. server.sendmail(...) handles it as necessary.
Jeff
A: 

That particular one gives me this:

Traceback (most recent call last):
  File "C:/Python26/08_emailconnects/12_29b_EmailfromStackOverload.py", line 19, in <module>
    server.starttls()
  File "C:\Python26\lib\smtplib.py", line 611, in starttls
    raise SMTPException("STARTTLS extension not supported by server.")
SMTPException: STARTTLS extension not supported by server.

Do I have firewall issues?

Chatter
Not an answer. Please update your question with these additional facts.
S.Lott
"StackOverload"? :D
Federico Ramponi
"STARTTLS extension not supported by server". Strange. It works from my box, and I guess we're using the same server. It's not a firewall issue, anyway - if ehlo() works without errors the connection is Ok.
Federico Ramponi
+2  A: 

Here's a simple throw away solution. Meant to paste this earlier, but fell asleep at my chair.

import smtplib
import email
import os

username = "[email protected]"
passwd = "password"

def 
mail(to, subject, text, attach):
   msg = MIMEMultipart()

   msg['From'] = username
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   part = MIMEBase('application', 'octet-stream')
   part.set_payload(open(attach, 'rb').read())
   Encoders.encode_base64(part)
   part.add_header('Content-Disposition',
           'attachment; filename="%s"' % os.path.basename(attach))
   msg.attach(part)

   server = smtplib.SMTP("smtp.gmail.com", 495)
   server.ehlo()
   server.starttls()
   server.ehlo()
   server.login(username, passwd)
   server.sendmail(username, to, msg.as_string())
   server.close()

   mail("you", "hi", "hi", "webcam.jpg")

It's my assumption that most people on this thread that have had successful attempts with their code aren't on win32. ;)

EndUsr
My code definitely needs 2 ehlo commands. Code does not work without ehlo.
Jiri
+1  A: 

Okay, found out that this line of code does the trick!

server = smtplib.SMTP('smtp.gmail.com', 587 )

Turned out to be GMAIL didn't support SSL on port 25 (and port 465 caused a hang for some reason).

Thanks guys!

Chatter
Well, written it on Dec 29: http://stackoverflow.com/questions/399129/failing-to-send-email-with-the-python-example#399140
Abgan
+1  A: 

The correct way to connect to GMail using SSL is:

server = smtplib.SMTP('smtp.gmail.com', 587)

Port 465 seems to cause delays. Both ports are specified in a GMail FAQ.

Note that use of port 587 is more common for SMTP over SSL, although this is just trivial information, it has no other practical use.

This answer is provided as community wiki in order to be chosen as "the" answer. Please improve as needed.

ΤΖΩΤΖΙΟΥ
+1  A: 

The problem is due to a bug in Python. Trying to create a connection with SMTP_SSL will fail with "SMTPServerDisconnected: please run connect() first."

A fix has been committed, so you can patch your local copy. See the attachment named "smtplib_72551.diff".

(Note: SMTP_SSL is a new class added to Python 2.6/3.0 and later.)

keithb
thanks, that worked for me
Paul