1. 程式人生 > >計算機網路(2)——手動SMTP

計算機網路(2)——手動SMTP

#file name:PA01_3.py
#writer:Zhang_Jingtun(Ordinary_Crazy)
#initial date:20180310
from socket import *
msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"

# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver =('smtp.163.com', 25)

# Create socket called clientSocket and establish a TCP connection with mailserver
#Fill in start
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(mailserver)
#Fill in end

recv = clientSocket.recv(1024)
print (recv)
if(str(recv[:3],"utf-8") != "220"):
	print('220 reply not received from server.')


# Send HELO command and print server response.
heloCommand = 'HELO Alice\r\n'
clientSocket.send(heloCommand.encode())
recv1 = clientSocket.recv(1024)
print (recv1)
if(str(recv1[:3],"utf-8") != '250'):
	print ('250 reply not received from server.')
	
loginCommand = 'AUTH LOGIN\r\n'
clientSocket.send(loginCommand.encode())
recv7 = clientSocket.recv(1024)
print (recv7)
if str(recv7[:3],"utf-8") != '334':
	print ('334 reply not received from server.')
	
	
clientSocket.send("使用者名稱base64碼\r\n".encode())
recv9 = clientSocket.recv(1024)
print (recv9)
clientSocket.send("密碼base64碼\r\n".encode())
recv8 = clientSocket.recv(1024)
print (recv8)
# Send MAIL FROM command and print server response.
# Fill in start

mail_fromCommand = 'MAIL FROM:<傳送郵箱全稱>\r\n'
clientSocket.send(mail_fromCommand.encode())
recv2 = clientSocket.recv(1024)
print (recv2)
if str(recv2[:3],"utf-8") != "250":
	print ('250 reply not received from server.')
# Fill in end

# Send RCPT TO command and print server response.
# Fill in start
rcpt_toCommand = 'RCPT TO:<接收郵箱quan chen>\r\n'
clientSocket.send(rcpt_toCommand.encode())
recv3 = clientSocket.recv(1024)
print (recv3)
if str(recv3[:3],"utf-8") != '250':
	print ('250 reply not received from server.')
# Fill in end

# Send DATA command and print server response.
# Fill in start
dataCommand = 'DATA\r\n'
clientSocket.send(dataCommand.encode())
recv4 = clientSocket.recv(1024)
print (recv4)
if str(recv4[:3],"utf-8") != '354':
	print ('354 reply not received from server.')
# Fill in end

# Send message data.
# Fill in start
message = "testmail\r\n"
clientSocket.send("from:傳送郵箱全稱\r\n".encode())
clientSocket.send("to:接收郵箱全稱\r\n".encode())
clientSocket.send("subject:test\r\n".encode())
clientSocket.send("\r\n".encode())
clientSocket.send(message.encode())
# Fill in end

# Message ends with a single period.
# Fill in start
clientSocket.send(".\r\n".encode())
recv5 = clientSocket.recv(1024)
print (recv5)
if str(recv5[:3],"utf-8") != '250':
	print ('250 reply not received from server.')
# Fill in end

# Send QUIT command and get server response.
# Fill in start
quitCommand = 'QUIT\r\n'
clientSocket.send(quitCommand.encode())
recv6 = clientSocket.recv(1024)
print (recv6)
if str(recv6[:3],"utf-8") != '221':
	print ('221 reply not received from server.')
# Fill in end