将消息附加到不存在的文件夹时,不会抛出任何错误。很难想象这是故意的,我做错了什么?
mailbox = imaplib.IMAP4_SSL(host="foo")
mailbox.login("foo", "bar")
try:
mailbox.append("DOES_NOT_EXIST", '', imaplib.Time2Internaldate(time.time()), str(mail).encode("utf-8"))
except:
# Expecting to fail here, but it doesn't
# Message doesn't show up in any other folder either (expectedly)
正如在comments中正确地指出的那样,这实际上是预期的行为和documented。
每个命令都返回一个元组:(type,[data,...])其中type通常是'OK'或'NO',而data是命令响应中的文本,或命令的强制结果。
因此,捕获错误的一种方法是:
status, data = mailbox.append("DOES_NOT_EXIST", '', imaplib.Time2Internaldate(time.time()), str(mail).encode("utf-8"))
if status == "NO":
# Catch it here