首页 > 解决方案 > 如何使用 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 模式下建立连接。我不确定。

标签: pythonpython-3.xgmailgmail-imapimaplib

解决方案


在这个问题中,我以只读模式打开了邮箱。因此我的程序无法在 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')

.


推荐阅读