Computer Networking: a Top-Down Approach About Lab 3: SMTP Lab
from socket import*import ssl
import sys
import base64
# sender & reciever
sent_from ='example@gmail.com'
sent_password =''# One of your App passwords
sent_to ='example@gmail.com'# Mail content
msg ='I love computer networks!'
info =(("From: %s\r\n"+"To: %s\r\n"+"Subject:labs\r\n"+"%s")%(sent_from,sent_to,msg))
endmsg ="\r\n.\r\n"# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver ='smtp.gmail.com'# Create socket called clientSocket and establish a TCP connection with mailserver
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((mailserver,587))
recv = clientSocket.recv(1024).decode()print(recv)if recv[:3]!='220':print('220 reply not received from server.')
sys.exit(0)print('establish success')# Send HELO command and print server response.
tlsComman ='HELO Alice\r\n'
clientSocket.sendall(tlsComman.encode())
recv = clientSocket.recv(1024).decode()print(recv)if recv[:3]!='250':print('220 reply not received from server.')
sys.exit(0)print("connect success")# TSL handshake
tlsComman ='STARTTLS \r\n'
clientSocket.sendall(tlsComman.encode())
recv = clientSocket.recv(1024).decode()if recv[:3]!='220':print('220 reply not received from server.')
sys.exit(0)
context = ssl.create_default_context()
clientSocket = context.wrap_socket(clientSocket, server_hostname=mailserver)print('TSL AUTH success')# Auth
s="\0%s\0%s"%(sent_from, sent_password)
responce = base64.b64encode(s.encode()).decode()
clientSocket.sendall(('AUTH PLAIN %s'% responce +'\r\n').encode())
recv = clientSocket.recv(1024).decode()if(recv[:3]=='503'):print('already authentication ')if(recv[:3]!='235'):print('235 reply not rece9ived from server.')
sys.exit(0)print('ACCOUNT AUTH success')# Send MAIL FROM command and priscnt server response.
clientSocket.sendall(('MAIL FROM: <'+ sent_from +'>\r\n').encode())
recv = clientSocket.recv(1024).decode()print(recv)if(recv[:3]!='250'):print('250 reply not received from server')
sys.exit(0)# Send RCPT TO command and print server response.
clientSocket.sendall(('RCPT TO: <'+ sent_to +'>\r\n').encode())
recv = clientSocket.recv(1024).decode()print(recv)if(recv[:3]!='250'):print('250 reply not received from server')
sys.exit(0)# Send DATA command and print server response.
dataCommand ='DATA\r\n'
clientSocket.send(dataCommand.encode())
recv = clientSocket.recv(1024).decode()print(recv)if(recv[:3]!='354'):print('354 reply not received from server')
sys.exit()# Send message data.
clientSocket.sendall(info.encode())# msg ends with a single period.
clientSocket.sendall(endmsg.encode())
recv = clientSocket.recv(1024).decode()print(recv)if(recv[:3]!='250'):print('250 reply not received from server')# Send QUIT command and get server response.
clientSocket.sendall('QUIT\r\n'.encode())
recv = clientSocket.recv(1024).decode()print(recv)if recv[:3]!='221':print('221 reply not received from server.')# Close connection
clientSocket.close()