from socket import *
import base64
# Choose a mail server
mailserver = 'smtp.163.com'
# Create socket called clientSocket and establish a TCP connection with mailserver
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((mailserver,25))
recv = clientSocket.recv(1024).decode()
print(recv)
if recv[:3] != '220':
print('220 reply not received from server.')
# Send HELO command and print server response.
heloCommand = 'HELO hi\r\n'
clientSocket.send(heloCommand.encode())
recv1 = clientSocket.recv(1024).decode()
print(recv1)
if recv1[:3] != '250':
print('250 reply not received from server.')
# Send MAIL FROM command and print server response.
clientSocket.send('AUTH LOGIN\r\n'.encode())
recv2 = clientSocket.recv(1024).decode()
print(recv2)
if recv2[:3] != '334':
print('334 reply not received from server.')
user = base64.b64encode(b'*****@163.com').decode()+'\r\n' #输入邮箱
password = base64.b64encode(b'**********').decode()+'\r\n' #**输入授权密码
clientSocket.send(user.encode())
recv3 = clientSocket.recv(1024).decode()
print(recv3)
clientSocket.send(password.encode())
recv4 = clientSocket.recv(1024).decode()
print(recv4)
clientSocket.send('MAIL FROM: <*****@163.com> \r\n'.encode())
recv5 = clientSocket.recv(1024)
print('mail from: ', recv5)
# Send RCPT TO command and print server response.
clientSocket.send('RCPT TO: <******@qq.com> \r\n'.encode())
recv6 =clientSocket.recv(1024)
print('rcpt to: ', recv6)
# Send DATA command and print server response.
data = b'DATA\r\n'
clientSocket.send(data)
recv7 = clientSocket.recv(1024)
print('data: ', recv7)
# Send message data. 注意格式From:nickname<邮箱地址>,否则会被qq邮箱拒收
header = "From:boss<****@163.com>\r\nTo:*********@qq.com\r\nSubject:a letter\r\n"
msg = 'hello,world'
clientSocket.send((header+msg).encode())
clientSocket.send('/r/n./r/n'.encode()) # end message
recv8 = clientSocket.recv(1024)
print(recv8)
# Send QUIT command and get server response.
clientSocket.send('QUIT\r\n'.encode())
clientSocket.close()