I am attempting to connect to the Gmail SMTP mail server and perform tasks as outlined by the skeleton code given to me. Only the use of socket
s is allowed (so not the smtplib
). I need to: send HELO
command, MAIL FROM
, RCPT TO
, and DATA
.
There are many cases of similar problems posted, but they haven't received the proper answer. For example: Implementing Transport Layer Security in Python - Simple Mail Client
The program is required to connect to smtp.gmail.com
over port 587
. I've taken two different approaches:
Using STARTTLS:
mailserver = 'smtp.gmail.com' clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((mailserver, 587)) recv = clientSocket.recv(1024) print recv if recv[:3] != '220': print '220 reply not received from server.' #Send HELO command and print server response heloCommand = 'HELO Alice\r\n' clientSocket.send(heloCommand) recv1 = clientSocket.recv(1024) print recv1 if recv1[:3] != '250': print '250 reply not received from server.' #Send MAIL FROM command and print server response. command = "STARTTLS\r\n" clientSocket.send(command) recvdiscard = clientSocket.recv(1024) print recvdiscard clientSocket.send("MAIL From: email\r\n") recv2 = clientSocket.recv(1024) print recv2 if recv2[:3] != '250': print '250 reply not received from server.'
Using SSL:
clientSocketSSL = ssl.wrap_socket(clientSocket)
Then
clientSocketSSL
replaces all instances ofclientSocket
. The STARTTLS lines are also removed andimport ssl
is added to the top.
When using the first method, the MAIL FROM:
command isn't returning anything. I'm getting the following output:
250 mx.google.com at your service
220 2.0.0 Ready to start TLS
250 reply not received from server.
When using SSL, I'm getting the same as the linked post:
ssl.SSLError: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Am I missing something here? I guess my best option is to use TLS but I have no idea how to go about that... is there something wrong with my MAIL FROM
command?
When using SSL, you need to connect to port 465 instead of port 587. If you use STARTTLS, you still need to use
ssl.wrap_socket
, you just do it later - specifically, after receiving the220
response to theSTARTTLS
command. After doingSTARTTLS
, you're supposed to doHELO
again, since the server is supposed to forget anything that happened before theSTARTTLS
.In either case, the servers at smtp.google.com ports 465 and 587 still won't return a
250
response to theMAIL
command, since they require that you are authenticated before you send mail. You'll get a530
response instead. You'll need to use theAUTH
command with your gmail.com credentials to authenticate before you can useMAIL
successfully on those servers.If you don't want to authenticate, and depending on the details of what you need to do, you could try using port 25 of the server found in gmail.com's MX record. At the moment, the server is gmail-smtp-in.l.google.com and supports STARTTLS.