我的 python 代碼選擇了一些郵件并將它們移動到另一個檔案夾。
# A.py
def __init__(self):
account = conf.account
password = conf.password
server = conf.imap_server
port = conf.imap_port
self.mail = imaplib.IMAP4_SSL(host=server, port=port)
try:
self.mail.login(account, password)
except imaplib.IMAP4.error as e:
self.logger.error("Cannot login to STMP server: %s" % str(e))
def move_handled_mails(self, mail_list, suffix=0):
archiving_folder = ''.join([str(current_year), '-', str(current_month), '-', str(suffix)])
self.mail.debug = 4
typ, data = self.mail.select(archiving_folder)
if typ != 'OK':
if "NONEXISTENT" in data[0].decode():
self.mail.create(archiving_folder)
typ, data = self.mail.select(archiving_folder)
if "Too many mail in folder" in data[0].decode():
return self.move_handled_mails(mail_list, suffix 1)
if typ != 'OK':
exit()
for num in mail_list:
print(num)
typ, data = self.mail.uid('COPY', num, archiving_folder)
if typ == 'OK':
typ, data = self.mail.uid('STORE', num, ' FLAGS', '(\\Deleted)')
if typ != 'OK':
exit()
print("Executing expunge")
typ, data = self.mail.expunge()
if typ != 'OK':
exit()
def run(self):
res, nums = self.mail.select() # default=INBOX
if res != 'OK':
self.logger.error(nums)
exit()
typ, msgnums = self.mail.uid('search', None, 'ALL')
mail_list = msgnums[0].split()
self.move_handled_mails(mail_list)
在該move_handled_mails方法中,創建檔案夾效果很好,但移動郵件不起作用。
此外,當我列印所有typS和dataS,它們被列印為OK和Nonerepectively。
運行代碼后,沒有發生錯誤,但也沒有移動郵件。
什么可能是問題,我應該如何除錯這個問題?
添加后除錯日志self.mail.debug=4:
Mail list: [b'7144291']
03:12.87 > b'GBDI2 SELECT 2021-11-0'
03:13.04 < b'* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)'
03:13.04 < b'* OK [PERMANENTFLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft \\*)] Flags permitted.'
03:13.04 < b'* 13534 EXISTS'
03:13.04 < b'* 0 RECENT'
03:13.04 < b'* OK [UNSEEN 1] First unseen.'
03:13.04 < b'* OK [UIDVALIDITY 119] UIDs valid'
03:13.04 < b'* OK [UIDNEXT 7129395] Predicted next UID'
03:13.04 < b'* OK [NOMODSEQ] No permanent modsequences'
03:13.04 < b'GBDI2 OK [READ-WRITE] Select completed.'
b'7144291'
03:13.04 > b'GBDI3 UID COPY 7144291 2021-11-0'
03:13.16 < b'GBDI3 OK No messages copied.'
03:13.16 > b'GBDI4 UID STORE 7144291 FLAGS (\\Deleted)'
03:13.30 < b'GBDI4 OK Store completed.'
Executing expunge
03:13.30 > b'GBDI5 EXPUNGE'
03:13.30 < b'GBDI5 OK Expunge completed.'
uj5u.com熱心網友回復:
不要select移動到檔案夾。 UIDs 僅在其源檔案夾中有意義。您正在切換到目標檔案夾,然后嘗試將郵件移出其中,但該郵件不存在。
洗掉這一行:
typ, data = self.mail.select(archiving_folder)
或者,至少,如果您需要它來檢查目標檔案夾是否存在,您必須切換回源檔案夾:self.mail.select('INBOX')或類似的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367891.html
