IMAP - get size of mailboxes

foten valinor at linuxmail.org
Tue Sep 14 08:31:42 EDT 2004


Jeff Epler <jepler at unpythonic.net> wrote in message news:<mailman.3239.1095092116.5135.python-list at python.org>...
> I played with imaplib a bit, and I think you want to use something like
>     # Find the first and last messages
>     m = [int(x) for x in msg[0].split()]
>     m.sort()
>     message set = "%d:%d" % (m[0], m[-1])
> 
>     # Get the RFC822.SIZE for each message
>     result, sizes response = M.fetch(message set, "(UID RFC822.SIZE)")
> .. and parse sizes response which looks like this:
>     >>> for i in range(10): print sizes response[i]
>     ... 
>     1 (UID 1 RFC822.SIZE 889)
>     2 (UID 3 RFC822.SIZE 3386)
>     3 (UID 4 RFC822.SIZE 2629)
>     4 (UID 5 RFC822.SIZE 989)
>     5 (UID 6 RFC822.SIZE 1566)
>     6 (UID 7 RFC822.SIZE 1591)
>     7 (UID 8 RFC822.SIZE 1894)
>     8 (UID 9 RFC822.SIZE 1546)
>     9 (UID 10 RFC822.SIZE 1372)
>     10 (UID 11 RFC822.SIZE 917)
> 
> Jeff
> 
> --

Thanx for your help! I think I have it working now. The speed is not bad at all.

//Fredrik

import sys, os, string, imaplib, getpass

imap_server = "myserver.com"

# Open a connection to the IMAP server
M = imaplib.IMAP4(imap_server)
M.login(getpass.getuser(), getpass.getpass())

# The list of all folders
result,list = M.list()

print "%-30s%5s%10s\n" % ("Folder", "# Msg", "Size")

number_of_messages_all = 0
size_all = 0

for item in list[:]:
    x = item.split()
    mailbox = string.join(x[2:])    

    # Select the desired folder
    result, number_of_messages  = M.select(mailbox, readonly=1)
    number_of_messages_all += int(number_of_messages[0])

    size_folder = 0
    # Go through all the messages in the selected folder
    typ, msg = M.search(None, 'ALL')
    # Find the first and last messages
    m = [int(x) for x in msg[0].split()]
    m.sort()
    if m:
        message_set = "%d:%d" % (m[0], m[-1])
        result, sizes_response = M.fetch(message_set, "(UID RFC822.SIZE)")
        for i in range(m[-1]):
            tmp = sizes_response[i].split()
            size_folder += int(tmp[-1].replace(')', ''))
    else:
        size_folder = 0
    print "%-30s%5d%10s" % (mailbox, int(number_of_messages[0]), size_folder);
    size_all += size_folder

print "\n%-30s%5i%10.3f MB\n" % ("Sum", number_of_messages_all, size_all/1e6)

# Close the connection
M.logout()



Result:
Folder                        # Msg      Size

Outbox                            0         0
Journal                           0         0
Drafts                           10     54245
Notes                            20     13265
PocketMirror                      1       500
"Sent Items"                    342   7054846
...
Sum                            3115    43.341 MB



More information about the Python-list mailing list