自顶向下的计算机网络作业——邮件客户实验题
作者:互联网
项目场景:
需要写一个邮件客户的程序,使得该程序能与邮件服务器创建一个tcp连接,使用SMTP协议与邮件服务器交谈。
直接附上源码:
from socket import *
import base64
#与qq邮箱服务器建立tcp连接,并且打印服务器返回的220,表示连接成功
serverName = 'smtp.163.com'
serverPort = 25
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"
recv = clientSocket.recv(1024).decode()
print(recv)
if recv[:3] != '220':
print('220 reply not received from server.')
#发送HELO命令,按照ASCII码的表示方法,每个报文以CRLF结束,CR表示回车,LF表示换行
heloCommand = 'HELO Alice\r\n'
clientSocket.send(heloCommand.encode())
recv1 = clientSocket.recv(1024).decode()
print(recv1)
if recv1[:3] != '250':
print('250 reply not received from server.')
#以auth login方式登录,返回username的base64编码
login = 'AUTH LOGIN\r\n'
clientSocket.send(login.encode())
recv2 = clientSocket.recv(1024)
print('login:',recv2.decode())
#输入用户名
username=base64.b64encode(b'--发送方用户名--@163.com').decode() + '\r\n'
clientSocket.send(username.encode())
recv_username = clientSocket.recv(1024)
print('username:', recv_username.decode())
#输入授权码,此处授权码需要使用163邮箱开启
password=base64.b64encode(b'--发送方授权码--').decode() + '\r\n'
clientSocket.send(password.encode())
recv_password = clientSocket.recv(1024)
print('password: ', recv_password.decode())
#发送Mail From命令,指定是发送方
MailFROM = 'Mail From:<--发送方名称--@163.com>\r\n'
clientSocket.send(MailFROM.encode())
recv3 = clientSocket.recv(1024).decode()
print(recv3)
#发送RCPT TO,指定接收方
RCPT = 'RCPT TO:<--接收方的名称--@qq.com>\r\n'
clientSocket.send(RCPT.encode())
recv4 = clientSocket.recv(1024).decode()
print(recv4)
#发送DATA命令,表明发送的邮件
DATA = 'DATA\r\n'
clientSocket.send(DATA.encode())
recv5 = clientSocket.recv(1024).decode()
print(recv5)
#发送的邮件必须符合163邮箱的格式,不然会被当成垃圾邮件发送
string1 = 'Curry is the best basketball player in the world.'+'\r\n'
string2 = 'And Micheal is the best dancer in the world.'+'\r\n'
END = '.\r\n'
who = 'zsya0807@163.com'
from_ = who
to = ['2424948099@qq.com']
headers = [
'From: %s' % from_,
'To: %s' % ','.join(to),
'Subject: send SMTP',
]
body = [
string1,
string2,
]
msg = '\r\n\r\n'.join(('\r\n'.join(headers), '\r\n'.join(body)))
clientSocket.send(msg.encode())
clientSocket.send(END.encode())
recv5 = clientSocket.recv(1024).decode()
print(recv5)
#发送QUIT命令,说明要退出
QUIT = "QUIT\r\n"
clientSocket.send(QUIT.encode())
recv6 = clientSocket.recv(1024).decode()
print(recv6)
问题描述:进行用户密码验证时出现错误
此处就算输入了正确的用户名和密码,依然会显示错误
password=base64.b64encode(b'asdf2389i23').decode() + '\r\n'
clientSocket.send(password.encode())
recv_password = clientSocket.recv(1024)
print('password: ', recv_password.decode())
原因分析:输入了自己的密码,没有输入验证码
163邮箱拒绝了第三方登录,因此屏蔽了这次验证
解决方案:
去163邮箱打开授权码
登录163邮箱,打开邮箱设置
在此处开去IMAP/SMTP服务以及POP3/SMTP服务,接下来验证后会受到此验证码,在第三方登录时不要输入自己的密码,输入此验证码
标签:decode,send,计算机网络,encode,自顶向下,邮件,print,recv,clientSocket 来源: https://blog.csdn.net/MichealCurry1/article/details/120628463