Sample code for 30+ languages & platforms
Ruby

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 Ruby Downloads

Ruby
require 'chilkat'

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 = Chilkat::CkImap.new()

imap.put_Ssl(true)
imap.put_Port(993)

success = imap.Connect("imap.example.com")
if (success == false)
    print imap.lastErrorText() + "\n";
    exit
end

success = imap.Login("user@example.com","myPassword")
if (success == false)
    print imap.lastErrorText() + "\n";
    exit
end

success = imap.SelectMailbox("Inbox")
if (success == false)
    print imap.lastErrorText() + "\n";
    exit
end

#  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 = Chilkat::CkEmail.new()
success = imap.FetchEmail(headersOnly,seqNum,useUid,email)
if (success == false)
    print imap.lastErrorText() + "\n";
    exit
end

numAttach = imap.GetMailNumAttach(email)

for i in 0 .. numAttach - 1
    fname = imap.getMailAttachFilename(email,i)
    if (imap.get_LastMethodSuccess() == false)
        print imap.lastErrorText() + "\n";
        exit
    end

    sz = imap.GetMailAttachSize(email,i)
    print fname + ": " + sz.to_s() + " bytes" + "\n";
end

success = imap.Disconnect()
if (success == false)
    print imap.lastErrorText() + "\n";
    exit
end