title: Connect to SMTP (SSL or TLS) using Python
body: <p>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 <code>socket</code>s is allowed (so not the <code>smtplib</code>). I need to: send <code>HELO</code> command, <code>MAIL FROM</code>, <code>RCPT TO</code>, and <code>DATA</code>.</p>
  
  <p>There are many cases of similar problems posted, but they haven't received the proper answer. For example:
  <a href="https://stackoverflow.com/questions/12549593/implementing-transport-layer-security-in-python-simple-mail-client">Implementing Transport Layer Security in Python - Simple Mail Client</a></p>
  
  <p>The program is required to connect to <code>smtp.gmail.com</code> over port <code>587</code>.  I've taken two different approaches:</p>
  
  <ol>
  <li><p>Using STARTTLS:</p>
  
  <pre><code>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.'
  </code></pre></li>
  <li><p>Using SSL:</p>
  
  <pre><code>clientSocketSSL = ssl.wrap_socket(clientSocket)
  </code></pre>
  
  <p>Then <code>clientSocketSSL</code> replaces all instances of <code>clientSocket</code>. The STARTTLS lines are also removed and <code>import ssl</code> is added to the top.</p></li>
  </ol>
  
  <p>When using the first method, the <code>MAIL FROM:</code> command isn't returning anything. I'm getting the following output:</p>
  
  <pre class="lang-none prettyprint-override"><code>250 mx.google.com at your service
  
  220 2.0.0 Ready to start TLS
  
  250 reply not received from server.
  </code></pre>
  
  <p>When using SSL, I'm getting the same as the linked post:</p>
  
  <pre class="lang-none prettyprint-override"><code>ssl.SSLError: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
  </code></pre>
  
  <p>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 <code>MAIL FROM</code> command?</p>