'ImapLib How can I limit the number of messages fetched?

I have many e-mail messages in the inbox which I am trying to clean up. I am using the following code I found on the net, but it is exceeding the Maxline limit. I tried increasing imaplib._MAXLINE as suggested in another post, very significantly, but even that is exceeded. How can I modify the code to fetch only say 1000 messages at a time? Additionally, what is the syntax to limit the messages fetched to a given date range? Thank you.

def fetch_message(conn, msg_uid ):
    """
    Fetch a specific message uid (not sequential id!) from the given folder;
    return the parsed message. User must ensure that specified
    message ID exists in that folder.
    """
    rv, data = conn.uid('fetch', msg_uid, "(RFC822)")
    if rv != 'OK':
        print ("ERROR fetching message #", msg_uid)
        return {}

    return email.message_from_bytes(data[0][1])  # dict-like object


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source