You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
p2l5wexnu/code/reference/ch_socket/SMTPClient.py

71 lines
2.4 KiB

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"
# 填写代码使程序发送的邮件中包含内容为 "Hello World!"。
msg = "Hello World!"
endmsg = "\r\n.\r\n"
#本地搭建的邮件服务器IP地址。
mailserver = 'localhost'
# 在端口25上启动邮件服务器。
mailport = 25
connectaddress = (mailserver, mailport)
# 创建 socket 和邮件服务器建立 TCP 连接。
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(connectaddress)
recv = clientSocket.recv(1024)
if recv.decode()[:3] != '220':
print ('220 reply not received from server.')
# 发送 HELO 命令,打印服务器响应。
heloCommand = 'HELO Alice\r\n'
clientSocket.send(bytes(heloCommand.encode()))
recv1 = clientSocket.recv(1024)
if recv1.decode()[:3] != '250':
print ('250 reply not received from server.')
#发送登陆认证信息
login = b'auth login\r\n'
clientSocket.send(login)
recv2 = clientSocket.recv(1024).decode('utf-8')
print ('登陆认证',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 ('用户名',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 ('密码',recv4)
# 发送 MAIL FROM 命令,打印服务器响应。
clientSocket.send(bytes(mailfrom.encode()))
check = clientSocket.recv(1024)
print(check)
# 发送 RCPT TO 命令,打印服务器响应。
clientSocket.send(bytes(rcptto.encode()))#将RCPT发送到命令和打印服务器响应。
check1 = clientSocket.recv(1024)
print(check1)
# 发送 DATA 命令,打印服务器响应。
clientSocket.send(bytes(data.encode()))#发送数据命令和打印服务器响应。
check2 = clientSocket.recv(1024)
print(check2)
# 发送邮件内容。消息以单个"." 结束。
clientSocket.send(bytes((mailfrom+msg+endmsg).encode()))#发送消息数据。
check3 = clientSocket.recv(1024)
print(check3)
# 发送 QUIT 命令,获取服务器响应。
clientSocket.send(bytes(quitmsg.encode()))
check4 = clientSocket.recv(1024)
print(check4)
clientSocket.close()