Search code examples
c#sizeimapattachmentmailkit

Check attachment size with mailkit


I'm downloading attachments for a given mailid with the following code:

HeaderSearchQuery searchCondition = SearchQuery.HeaderContains("Message-Id", ssMailItemId);

                var folder = client.GetFolder(ssFolderName);
                folder.Open(FolderAccess.ReadOnly);

                IList<UniqueId> ids = folder.Search(searchCondition);

                foreach (UniqueId uniqueId in ids)
                {
                    MimeMessage message = folder.GetMessage(uniqueId);

                    foreach (MimeEntity attachment in message.Attachments)
                    {
                        ssAttachmentsDetail.Append(fillAttachmentDetailRecord(attachment, uniqueId.Id.ToString()));
                    }

But both the MimeEntity.ContentDisposition.Size and MimePart.ContentDuration are null. Is there any field regarding the size of the attachment?


Solution

  • The ContentDisposition.Size property is only set if the Content-Disposition header has a size parameter, like this:

    Content-Disposition: attachment; size=15462

    But that value should probably not really be trusted anyway...

    If you want the size of an attachment, the only accurate way of doing this would be to do something like this:

    // specify that we want to fill the IMessageSummary.Body and IMessageSummary.UniqueId fields...
    var items = folder.Fetch (ids, MessageSummaryItems.BodyStructure | MessageSummaryItems.UniqueId);
    foreach (var item in items) {
        foreach (var attachment in item.Attachments) {
            // 'octets' is just a fancy word for "number of bytes"
            var size = attachment.Octets;
    
            // download the individual attachment
            var entity = folder.GetBodyPart (item.UniqueId, attachment);
        }
    }