【问题标题】:How to delete email from gmail using python IMAP?如何使用 python IMAP 从 gmail 中删除电子邮件?
【发布时间】:2021-01-11 22:45:03
【问题描述】:

我正在尝试从邮件中读取 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 模式下建立连接。我不确定。

【问题讨论】:

  • 请阅读this article。这个问题似乎是在询问如何使用google mail api 删除邮件,但它没有被标记为这样。您还没有说您尝试做什么来解决它,或者您是否尝试过调试,提供有关错误消息的任何信息,提供有关您正在使用的库或平台的任何信息。请使用此信息更新您的问题。
  • 我不想使用 gmail api。我正在尝试使用 IMAP 阅读和删除电子邮件。我能够阅读邮件,但无法删除该邮件。我还提到了代码中哪个部分不起作用的注释。我认为您应该再次阅读问题,以便正确理解问题。
  • 你是对的@ameya,对不起,我认为这是一个 api 问题。祝你好运!

标签: python python-3.x gmail gmail-imap imaplib


【解决方案1】:

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

.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-02
    • 2010-12-19
    • 1970-01-01
    • 2018-11-02
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多