如何用Python的smtpd DebuggingServer输出解码后的Base64编码邮件
解决Python SMTP DebuggingServer显示Base64编码乱码的问题
我之前也被这个问题折腾过!默认的DebuggingServer实在太“直白”——它只会把收到的原始字节数据原封不动打印出来,完全不处理MIME邮件的编码和解码逻辑,导致Base64编码的内容看起来全是乱码,根本没法直接查看邮件的实际内容。
给你分享一个我自己在用的解决方案:自定义一个能自动解析MIME并解码Base64的调试服务器类,替换默认的DebuggingServer。
步骤1:编写自定义调试服务器脚本
创建一个名为smtp-debug-server.py的文件,内容如下:
import asyncore from smtpd import SMTPServer from email import policy from email.parser import BytesParser class DecodingDebuggingServer(SMTPServer): def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): print("---------- MESSAGE FOLLOWS ----------") # 解析MIME邮件结构 msg = BytesParser(policy=policy.default).parsebytes(data) # 打印核心邮件头部信息 print(f"From: {msg['From']}") print(f"To: {msg['To']}") print(f"Subject: {msg['Subject']}") print(f"MIME-Version: {msg['MIME-Version']}") print(f"X-Peer: {peer[0]}") print("\n--- 邮件内容 ---") # 处理多类型邮件 if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() if content_type == 'text/plain': # 解码纯文本内容 content = part.get_content() print(f"[纯文本内容]\n{content}\n") elif content_type == 'text/html': # 解码HTML内容,只显示前500字符避免输出过长 content = part.get_content() print(f"[HTML内容]\n{content[:500]}...\n") else: # 单部分邮件直接解码输出 content = msg.get_content() print(content) print("---------- END MESSAGE ----------") if __name__ == "__main__": server = DecodingDebuggingServer(('localhost', 1025), None) print("Decoding SMTP Debug Server running on localhost:1025...") try: asyncore.loop() except KeyboardInterrupt: print("\nServer stopped.")
步骤2:运行自定义服务器
在终端执行以下命令启动服务器:
python smtp-debug-server.py
步骤3:测试发送邮件
现在让你的应用往localhost:1025发送邮件,服务器会自动解析MIME结构,把Base64编码的内容解码成可读的文本/HTML内容打印出来,再也不用对着一堆乱码头疼了!
补充说明
- 如果不需要HTML内容预览,可以把脚本中对应HTML处理的代码块删掉;
- 如果需要处理附件,可以在
msg.walk()的循环里添加对附件类型(比如application/octet-stream)的判断逻辑。
内容的提问来源于stack exchange,提问作者BiAiB
相关产品推荐
相关产品推荐

