我必須在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