Search IMAP folder for messages with attachments

IMAP protocol does not define any syntax to search for attachments. How to work around this?

1. E-mails with attachments usually have “multipart/mixed” Content-Type (this is not always so but close to that). As the IMAP protocol defines HEADER search key, this seems to be the correct syntax:

 

UidCollection uids = (UidCollection)imp.Search(true, "HEADER Content-Type \"multipart/mixed\"" , null);

imp is Imap class instance, already connected to your mail account.

Unfortunately, this won’t work as most mail servers nowadays don’t index Content-Type headers. They should but they don’t.

2. If the above doesn’t work with your IMAP server (what a surprise!), the only choice you have is to download IMAP body structures for all messages in the folder and parse them. This is slower than SEARCH command but still much faster than downloading entire messages. Also, this approach is more accurate as “multipart/mixed” is not a perfect guarantee for a message to actually contain attachments.

EnvelopeCollection envs = imp.DownloadEnvelopes(Imap.AllMessages, false, EnvelopeParts.BodyStructure, 0);
foreach (Envelope env in envs)
{	
	bool hasAttachments = false;
	ImapBodyStructureCollection parts = env.BodyStructure.GetAllParts();
	foreach (ImapBodyStructure part in parts)
	{
		// Detect if this part is attachment.
		if ((part.Disposition != null && part.Disposition.ToLower() == "attachment") ||
			(part.Filename != null && part.Filename != string.Empty) ||
			(part.ContentType != null && part.ContentType.ToLower() == "message/rfc822"))
		{
			hasAttachments = true;
			break;
		}
	}
}

The code snipped above was adapted from this more complex sample.

Search IMAP folder for messages with attachments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s