python - 如何使用 python IMAP 从 gmail 中删除电子邮件?
问题描述
我正在尝试从邮件中读取 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')
.
推荐阅读
- php - has_header_image() 中未定义的偏移量
- matlab - Simulink 中的在线多项式曲线拟合
- c++ - 如何强制使用 SFML_DIR?
- css - 如何在 Chrome on Rails 中使用 FontAwesome 5?
- firebase - 如何在不登录的情况下将用户数据保存在数据库中?
- javascript - 下拉菜单自动更新按钮的 URL
- python - 如何获取bugzilla登录的api token
- python - Python(tkinter)获取检查了哪些检查按钮?
- java - Webdriver 在使用 selenium + cucumber + Page Factory Model 开发的框架上在功能文件执行时返回 null
- r - 在 RStudio 中打包 Metatrader