python socket - smtp gmail没有从' DATA'中返回任何内容。内容行

时间:2018-01-30 04:23:07

标签: python sockets smtp gmail

代码在写“' body' DATA命令(消息内容以一行只包含'。' char)结束。

Socket只是一直等待.recv()消息 - 没有返回错误代码。如果设置了socket.timeout()选项,它只会输出“没有收到任何内容”。错误。

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.")

1 个答案:

答案 0 :(得分:0)

另一个SMTP服务器期望\r\n为行尾,所以目前你还没有完全停止,即\r\n.\r\n

因此,您只需将最后一行更改为

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

添加额外的\r