EthanLWillis
EthanLWillis

Reputation: 950

How to connect to gmail with sockets over ssl in Python

So far my code is as follows:

from socket import *
import ssl
msg = "\r\n smtp..."
endmsg = "\r\n.\r\n"

# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver = ("smtp.gmail.com", 587)

# Create socket called clientSocket and establish a TCP connection with mailserver over SSL
clientSocket = socket(AF_INET, SOCK_STREAM);
clientSocket = ssl.wrap_socket(clientSocket, ssl_version=ssl.PROTOCOL_SSLv23)
clientSocket.connect(mailserver)

#Print server response
recv = clientSocket.recv(1024)
print recv
if recv[:3] != '220':
print '220 reply not received from server.'

I get the error message ssl.SSLERrror: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol when attempting to run this script. At other times I've gotten errors regarding the server not responding in time.

Does anyone have any clues about what I'm doing wrong? (And yes I know I could use smtplib for dealing smtp servers, but this is an exercise)

Upvotes: 1

Views: 5805

Answers (1)

tMC
tMC

Reputation: 19355

port 587 is not encrypted.

telnet smtp.gmail.com 587

Trying 74.125.142.109...
Connected to gmail-smtp-msa.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP aa4sm9457625igc.15
helo test.com
250 mx.google.com at your service

Upvotes: 2

Related Questions