我必须在Python中为类编写一个SMTP邮件客户端,并且卡在作业的第一部分。经过很多麻烦我已经得到了这么多(目前使用免费的便携式SMTP服务器,但以后需要使用SSL或TLS的Gmail)。以下是我的代码。当它到达代码的RCPT TO部分时,我得到一个500语法错误。谁能帮忙?SMTP邮件客户端Python
from socket import *
msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"
# Choose a mail server
mailServer = 'localhost'
mailPort = 25
# Create socket called clientSocket and establish a TCP connection with mailserver
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((mailServer, mailPort))
recv = clientSocket.recv(1024)
print 'test'
print recv
if recv[:3] != '220':
print '220 reply not received from server.'
# Send HELLO command and print server response.
helloCommand = 'HELO Alice\r\n';
clientSocket.send(helloCommand)
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)
#recva = clientSocket.recv(1024)
#print(recva)
mailfromCommand = 'MAIL FROM: <[email protected]>\r\n.'
clientSocket.send(mailfromCommand)
recv1 = clientSocket.recv(1024)
print(recv1)
if recv1[:3] != '250':
print('mail from 250 reply not received from server.')
# Send RCPT TO command and print server response.
rcpttoCommand = 'RCPT TO: <[email protected]>\r\n'
clientSocket.send(rcpttoCommand)
recv1 = clientSocket.recv(1024)
print(recv1)
if recv1[:3] != '250':
print('rcpt to 250 reply not received from server.')
# Send DATA command and print server response
dataCommand = 'Data'
print(dataCommand)
clientSocket.send(dataCommand)
recv1 = clientSocket.recv(1024)
print(recv1)
if recv1[:3] != '250':
print('data 250 reply not received from server.')
# Send message data.
message = raw_input('Enter Message Here: ')
# Fill in end# Message ends with a single period.
mailMessageEnd = '\r\n.\r\n'
clientSocket.send(message + mailMessageEnd)
recv1 = clientSocket.recv(1024)
print(recv1)
if recv1[:3] != '250':
print('end msg 250 reply not received from server.')
# Send QUIT command and get server response.
quitCommand = 'Quit\r\n'
print(quitCommand)
clientSocket.send(quitCommand)
recv1 = clientSocket.recv(1024)
print(recv1)
if recv1[:3] != '250':
print('quit 250 reply not received from server.')
pass
if __name__ == '__main__':
main()
结果:
test
220 localhost
250 Hello localhost
250 [email protected] Address Okay
RCPT TO: <[email protected]>
500 Syntax Error
rcpt to 250 reply not received from server.
Data
您是否被禁止使用标准库和/或第三方软件包中的['smtplib'](http://docs.python.org/2/library/smtplib.html)? – abarnert
同时,[TCP套接字是字节流,而不是消息流](http://stupidpythonideas.blogspot.com/2013/05/sockets-are-byte-streams-not-message.html)。每个'recv'可以从服务器获得半行数据,或者七个半行;你不能假设每个人都得到一条线。你需要缓冲和解析。或者只是使用'makefile'让Python做到这一点(它适用于像SMTP这样的任何一行一行的协议),并且使用'sendall'而不是'send',就完成了。 – abarnert
我们得到了一个基本的骨架代码,直到MAIL FROM命令完成。之后,我们必须填写其余的。 – user2946832