[英]How to delete email from gmail using python IMAP?
我正在嘗試從郵件中讀取 otp,然后我想從 gmail 選項中刪除該電子郵件。 我閱讀電子郵件沒有問題,但我無法刪除郵件。 我嘗試了 stackoverflow 中的一些代碼。 下面是我的代碼。
def getOtpMail(vEmail, vPaasword):
connection = imaplib.IMAP4_SSL(IMAP_URL) # stablish connection with IMAP server
try:
connection.login(vEmail, vPaasword) # Login with userid password
except Exception as e:
print(e)
return
loopLock = True
while loopLock:
# fetch
connection.select('"INBOX"', readonly=True)
retCode, messages = connection.search(None, '(UNSEEN)')
print(messages[0])
latest = int(messages[0].split()[-1])
res, msg = connection.fetch(str(latest), "(RFC822)")
for response in msg:
if isinstance(response, tuple):
print('\n------------email--------------\n')
msg = email.message_from_bytes(response[1])
if SENDER_NAME in msg['From'] and KEYWORD in msg['Subject']:
loopLock = False
# fetch required information
for part in msg.walk():
body = part.get_payload()
word_list = body.split()
index = word_list.index('verification')
otp = word_list[index + 3].strip('.')
#delete mail - below two line not working
connection.store(str(latest), '+FLAGS', '"[Gmail]/Trash"')
print(connection.expunge())
return otp
else:
continue
我閱讀了文檔並打印了connection.expunge()
所以我得到的響應為('NO', [b'EXPUNGE attempt on READ-ONLY folder (Failure)'])
。 我認為問題我必須在 WRITE 模式下建立連接。 我不確定。
在本期中,我以只讀模式打開郵箱。 因此我的程序無法在 IMAP 服務器中寫入和存儲。 我變了
connection.select('"INBOX"', readonly=True)
到
connection.select('"INBOX"', readonly=False)
我還更改了 store 方法中的命令類型和標志類型 -
connection.store(str(latest), '+FLAGS', '"[Gmail]/Trash"')
到
connection.store(str(latest), '+FLAGS', '\\Deleted')
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.