[英]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.