from socket import *
from base64 import *

mailfrom = "mail from:2@test.com\r\n"
rcptto = "rcpt to:1@test.com\r\n"
data = "data\r\n"
quitmsg = "quit\r\n"

msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"
#此处使用易邮邮件服务器软件搭建了一个内网邮件服务器
mailserver = '10.130.82.62'
mailport = 25
connectaddress = (mailserver, mailport)
# Create socket called clientSocket and establish a TCP connection with mailserver
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(connectaddress)

recv = clientSocket.recv(1024)
print (recv)
if recv[:3] != '220':
    print ('220 reply not received from server.')
# Send HELO command and print server response.
heloCommand = 'HELO Alice\r\n'
clientSocket.send(bytes(heloCommand.encode()))
recv1 = clientSocket.recv(1024)
print (recv1.decode())
if recv1[:3] != '250':
    print ('250 reply not received from server.')

#print('000000000000000')
#从命令和打印服务器响应发送邮件。
login = b'auth login\r\n'
clientSocket.send(login)
recv2 = clientSocket.recv(1024).decode('utf-8')
print ('222+',recv2)

userCommand = b64encode('2@test.com'.encode('utf-8'))
clientSocket.send((str(userCommand,encoding='utf-8')+'\r\n').encode())
recv3 = clientSocket.recv(1024).decode('utf-8')
print ('333+',recv3)

password = b64encode('2'.encode('utf-8'))
clientSocket.send((str(password,encoding='utf-8')+'\r\n').encode())
recv4 = clientSocket.recv(1024).decode('utf-8')
print ('444+',recv4)

#print('0000000000000000')

clientSocket.send(bytes(mailfrom.encode()))
check = clientSocket.recv(1024)
print(check)
clientSocket.send(bytes(rcptto.encode()))#将RCPT发送到命令和打印服务器响应。
check1 = clientSocket.recv(1024)
print(check1)
clientSocket.send(bytes(data.encode()))#发送数据命令和打印服务器响应。
check2 = clientSocket.recv(1024)
print(check2)
clientSocket.send(bytes((mailfrom+msg+endmsg).encode()))#发送消息数据。
check3 = clientSocket.recv(1024)
print(check3)
#发送退出命令并获得服务器响应。
clientSocket.send(bytes(quitmsg.encode()))
check4 = clientSocket.recv(1024)
print(check4)
clientSocket.close()
