[Python] imaplib2 | Is this behavior correct? The .uid() method returns different values ​in...

Discussão em 'Python' iniciado por Stack, Julho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am not a programming pro, but I managed to find the following feature when using the .uid() method.

    If the email address has unread messages that arrived before authorization and the first call to the method, then upon authorization and subsequent use of this method we will receive data of the following type:

    ('OK', [(b'820 (UID 560646 FLAGS (\\Seen NonJunk) RFC822 {1635}', b'Return-Path: …and so on…
Transfer-Encoding: base64\r\n\r\n….+\r\n’), b')'])

    But if, for example, we want to track the receipt of new unread messages in real time (in my case using an infinite loop), then after authorization and calling the .uid() method we get a tuple with a different format:

    ('OK', [b'820 (FLAGS (NonJunk))', (b'820 (UID 560646 FLAGS (\\Seen NonJunk) RFC822 {1635}', b'Return-Path: …and so on…
Transfer-Encoding: base64\r\n\r\n…Y+\r\n'), b')'])

    That is, unread messages received before authorization and unread messages received after authorization are read differently by the .uid() method?

    This creates problems when trying to decode the message using email.message_from_bytes()

    Maybe this is a bug? Or is the problem on my side?

    Here is an example of my code:

    class IMAPMail(imaplib2.IMAP4_SSL):
    def __init__(self, host):
    try:
    super().__init__(host=host)
    except Exception as Err:
    print(f'Error: {Err}')
    exit()

    def connect(self, user, password, mailbox):
    try:
    self.login(user, password)
    self.select(mailbox)
    except Exception as Err:
    print(f'Error: {Err}')
    return False

    def get_message_data(self, uids):
    for message_uid in uids:
    message_data = self.uid('fetch', message_uid, '(RFC822)')
    message_data_decode = email.message_from_bytes(message_data[1][0][1])
    return message_data_decode


    from mylib import IMAPMail


    mail = IMAPMail('imap.mail.com')
    mail.connect('user@mail.com', 'mypassword123', 'INBOX')

    while True:
    status, message_uids = mail.uid('search', 'UNSEEN')
    message_uids = messages_uids[0].split()

    if status != 'OK':
    print('Error!')

    if len(message_uids) >= 1:
    message_data = mail.get_message_data(message_uids)
    print(message_data)
    ...

    time.sleep(15)


    I found a solution to the problem in getting data not from the beginning of the tuple, but from its end. But I'm still interested in what the problem is

    Continue reading...

Compartilhe esta Página