Search code examples
pythonsocketssmtpgmail

python socket - smtp gmail returns nothing from 'DATA' content line


Code works fine up to writing the 'body' of the DATA command (message content that ends with a line containing nothing but a '.' char).

Socket simply keeps waiting for a .recv() message - no error code returned. If a socket.timeout() option is set, it just prints a 'nothing received' error.

address    = "smtp.gmail.com"
port       = 465
mailserver = (address, port)

sockplain = socket.socket(socket.AF_INET) 
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1

sockssl = context.wrap_socket(sockplain, server_hostname=address)
sockssl.connect(mailserver)

def sendToSMTPserver(*vararg):
    email_address = "email address goes here"
    message_code  = "SMTP code goes here e.g. 'RCPT TO'"
    mailFrom      = "complete message goes here"

    if len(vararg) > 1:
        message_code, username = vararg
        mailFrom = message_code + ":" + username + "\r\n"
    else:
        message_code = vararg[0]
        mailFrom = message_code + "\r\n"

    sockssl.send(mailFrom.encode())
    print(sockssl.recv(1024))

sendToSMTPserver("EHLO Alice")
sendToSMTPserver("AUTH LOGIN")
sendToSMTPserver(base64.b64encode(username))
sendToSMTPserver(base64.b64encode(password))
sendToSMTPserver("MAIL FROM", "<" + username + ">")
sendToSMTPserver("RCPT TO",   "<" + username + ">")
sendToSMTPserver("DATA")

# works fine until here ...

sendToSMTPserver("hangs after sending this line \n.")

Solution

  • The other SMTP server is expecting \r\n for the end of lines, so at the moment you don't have a full stop on its own line, i.e. \r\n.\r\n

    So, you need to simply change the last line to

    sendToSMTPserver("hangs after sending this line \r\n.")
    

    Adding a extra \r