我编写了一个使用 smtplib 发送电子邮件的简单程序。该程序完美运行并发送电子邮件。有没有什么选项可以让我在通信期间查看所有日志?意思是可以打印或查看发生的 smtp 对话吗?
问问题
104 次
1 回答
0
首先,您应该检查文档smtplib
- 请参阅set_debuglevel
with smtplib.SMTP_SSL(f'{host}:{port}') as server:
server.set_debuglevel(1)
server.login(login, password)
server.sendmail(sender_email, recipients, message.as_string())
因为.set_debuglevel(1)
它显示
send: 'ehlo [127.0.1.1]\r\n'
reply: b'250-smtp.googlemail.com at your service, [79.163.228.253]\r\n'
reply: b'250-SIZE 35882577\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\r\n'
reply: b'250-ENHANCEDSTATUSCODES\r\n'
reply: b'250-PIPELINING\r\n'
reply: b'250-CHUNKING\r\n'
reply: b'250 SMTPUTF8\r\n'
reply: retcode (250); Msg: b'smtp.googlemail.com at your service, [79.163.228.253]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8'
send: 'AUTH PLAIN ********\r\n'
reply: b'235 2.7.0 Accepted\r\n'
reply: retcode (235); Msg: b'2.7.0 Accepted'
因为.set_debuglevel(2)
它添加了时间戳
21:26:26.602350 send: 'ehlo [127.0.1.1]\r\n'
21:26:26.632756 reply: b'250-smtp.googlemail.com at your service, [79.163.228.253]\r\n'
21:26:26.632871 reply: b'250-SIZE 35882577\r\n'
21:26:26.632917 reply: b'250-8BITMIME\r\n'
21:26:26.632957 reply: b'250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\r\n'
21:26:26.633022 reply: b'250-ENHANCEDSTATUSCODES\r\n'
21:26:26.633072 reply: b'250-PIPELINING\r\n'
21:26:26.633112 reply: b'250-CHUNKING\r\n'
21:26:26.633151 reply: b'250 SMTPUTF8\r\n'
21:26:26.633201 reply: retcode (250); Msg: b'smtp.googlemail.com at your service, [79.163.228.253]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8'
它会发送它,standard error
因此如果您想将其放入文件中,'output.txt'
则必须重定向sys.stderr
import sys
old_stderr = sys.stderr
sys.stderr = open('output.txt', 'w')
with smtplib.SMTP_SSL(f'{host}:{port}') as server:
server.set_debuglevel(1)
server.login(login, password)
server.sendmail(sender_email, recipients, message.as_string())
sys.stderr = old_stderr
于 2021-11-04T20:20:10.620 回答