提问人:Fizufa 提问时间:10/27/2023 最后编辑:Fizufa 更新时间:10/27/2023 访问量:42
Python 中的套接字编程 - 发送邮件时的 SMTP 服务器
Socket Programming in Python - SMTP server on sending mail
问:
我正在尝试在发送邮件时使用SMTP服务器。
这是我 user.py SMTP 函数:
def smtp():
conn = SMTP('localhost', int(fdns_query(SMTP_SERVER, 'P')))
to = []
while True:
_to = input('To: ')
if _to == '':
break
to.append(_to)
subject = input('Subject: ')
content = input('Content: ')
msg = MIMEText(content, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = args.email
conn.sendmail(args.email, to, msg.as_string())
conn.quit()
if __name__ == '__main__':
while True:
try:
cmd = input('[smtp|pop|exit]>>> ')
if cmd == 'smtp':
smtp()
elif cmd == 'pop':
pop()
elif cmd == 'exit':
break
else:
print('Invalid command')
except KeyboardInterrupt:
break
except Exception as e:
print('-ERR in agent.py!!!!!')
print(repr(e))
这是 server.py:
class SMTPServer(BaseRequestHandler):
def handle(self):
conn = self.request
conn.sendall(b'220 Welcome to the SMTP server\r\n')
sender = None
recipients = []
hostname = socket.gethostname()
while True:
data = conn.recv(1024)
if not data:
break
command = data.decode().strip()
print(command)
if command.startswith('HELO') or command.startswith('EHLO'):
#conn.sendall(b'250 Hello\r\n')
#conn.sendall(b'250 Hello ' + command.split(' ')[1] + b'\r\n')
#conn.sendall(b'250-localhost Hello\r\n')
conn.sendall(f'250 Hello {hostname}\r\n'.encode())
elif command.startswith('MAIL FROM'):
sender = command.split('<')[1].split('>')[0]
conn.sendall(b'250 Sender OK\r\n')
elif command.startswith('RCPT TO'):
recipient = command.split('<')[1].split('>')[0]
recipients = ast.literal_eval(recipient)
conn.sendall(b'250 Recipient OK\r\n')
elif command == 'DATA':
conn.sendall(b'354 Start mail input; end with <CRLF>.<CRLF>\r\n')
mail_content = []
# line = conn.recv(1024).decode()
# if line.strip() == '.':
# break
# mail_content.append(line)
while True:
line = conn.recv(1024).decode()
if line.strip() == '.':
break
mail_content.append(line)
for recipient in recipients:
if recipient in MAILBOXES:
MAILBOXES[recipient].append(mail_content)
else:
print(f"Recipient {recipient} not found in MAILBOXES.")
conn.sendall(b'250 Mail accepted\r\n')
print(f"Sender: {sender}")
print(f"Recipients: {', '.join(recipients)}")
print("Mail Content:")
print("\n".join(mail_content))
sender = None
recipients = []
elif command == 'QUIT':
conn.sendall(b'221 Bye\r\n')
break
else:
conn.sendall(b'500 Syntax error\r\n')
我已经通过以下方式打开服务器: python3 server.py -n [服务器]
并在另一个 cmd 中运行以下命令: pyhton3 user.py -e [电子邮件地址] -p [密码]
但是我遇到了以下错误:
[smtp|pop|exit]>>> smtp
To: [email]
To:
Subject: Hiii
Content: I am emailing myself
-ERR in agent.py!!!!!
SMTPHeloError(500, b'Syntax error')
谁能帮我修复分析错误?SMTPServer(BaseRequestHandler)有问题吗?它不断抛出 500,语法错误。谢谢
答: 暂无答案
评论
ERR in agent.py
print(command)
SMTP.set_debug_level