Sample code for 30+ languages & platforms
Chilkat2-Python

Get IMAP Attachment Sizes

See more IMAP Examples

Demonstrates the Chilkat Imap.GetMailAttachSize method, which returns the size in bytes of an attachment. The first argument is the Email and the second is the zero-based attachment index. This example fetches headers only and prints each attachment's name and size.

Background: Like the attachment filename, the size comes from ckx-imap-* metadata and is available from a header-only fetch without downloading the body. A client can therefore show attachment sizes in a message preview, and decide whether to auto-download or prompt before pulling a large file.

Chilkat Chilkat2-Python Downloads

Chilkat2-Python
import sys
import chilkat2

success = False

# Demonstrates the Imap.GetMailAttachSize method, which returns the size in bytes of an
# attachment.  The 1st argument is the Email and the 2nd is the zero-based attachment index.

imap = chilkat2.Imap()

imap.Ssl = True
imap.Port = 993

success = imap.Connect("imap.example.com")
if (success == False):
    print(imap.LastErrorText)
    sys.exit()

success = imap.Login("user@example.com","myPassword")
if (success == False):
    print(imap.LastErrorText)
    sys.exit()

success = imap.SelectMailbox("Inbox")
if (success == False):
    print(imap.LastErrorText)
    sys.exit()

# Fetch only the message headers.  Attachment bodies are NOT downloaded, but the ckx-imap-*
# metadata describing the attachments is present, so the attachment info methods still work.
headersOnly = True
useUid = False
seqNum = 1
email = chilkat2.Email()
success = imap.FetchEmail(headersOnly,seqNum,useUid,email)
if (success == False):
    print(imap.LastErrorText)
    sys.exit()

numAttach = imap.GetMailNumAttach(email)

for i in range(0,numAttach):
    fname = imap.GetMailAttachFilename(email,i)
    if (imap.LastMethodSuccess == False):
        print(imap.LastErrorText)
        sys.exit()

    sz = imap.GetMailAttachSize(email,i)
    print(fname + ": " + str(sz) + " bytes")

success = imap.Disconnect()
if (success == False):
    print(imap.LastErrorText)
    sys.exit()