One reader recently asked how he could use my InfiniTec.Exchange library to scan the mails in the inbox folder of a users mailbox for attachments. Here is an example:
1 classProgram
2 {
3 staticvoid Main(string[] args)
4 {
5 ServicePointManager.ServerCertificateValidationCallback = delegate { returntrue; };
6
7 using (Connection connection = newConnection("server", ConnectionProtocol.Secure, newCredential("username", "password", AuthenticationType.Ntlm)))
8 {
9 Mailbox mbx;
10
11 Console.Out.WriteLine("Refreshing mailbox....");
12 mbx = newMailbox("exchange/useralias", connection);
13 mbx.Refresh();
14
15 ItemCollection<MessageItem> children = mbx.Inbox.ChildItems;
16
17 children.Constraints +=
18 string.Format("AND Cast(\"{0}\" as \"boolean\") = true", WellknownProperties.Item.HasAttachments);
19
20 Console.Out.WriteLine("Enumerating child items with attachments in inbox...");
21
22 children.Refresh();
23
24 Console.Out.WriteLine("Found {0} items", children.Count);
25
26 foreach (MessageItem item in children)
27 {
28 Console.Out.WriteLine("Processing " + item.Subject);
29 item.Attachments.Refresh();
30
31 foreach (Attachment attachment in item.Attachments)
32 {
33 Console.Out.WriteLine("\t{0} ({1}, {2}, {3} bytes)", attachment.Name, attachment.MimeType, attachment.ContentDisposition, attachment.Size);
34 }
35 }
36
37 Console.Out.WriteLine("Finished");
38 Console.ReadLine();
39 }
40 }
41 }
This is a console application, so you'll just have to replace the main class of a newly created console application with this code. Then, add a reference to my library (At least version 0.99.2).
The most tricky part here clearly is the modification of the constraints in line 17; The default constraint is initialized with this value:
1 _Searcher.Constraints = string.Format(CultureInfo.InvariantCulture, "(\"{0}\" = false) ", WellknownProperties.Dav.IsFolder);
This restricts the result set to child elements which are not folders. To restrict the result set further, you can just append additional constraints with an "AND". The full constraint being used here is this:
1 ("DAV:isfolder" = false) AND Cast("http://schemas.microsoft.com/mapi/proptag/xe1b000b" as "boolean") = true
You'll probably wonder why I used the MAPI property 0xe1b00b instead of the urn:schemas:httpmail:hasattachment property. In the past, I've found the latter property not very reliable - it was false, even though a message had an attachment. And since I'm using a non-standard property here, I have to cast it to boolean to make the request work. If you don't do this, you'll end up with a Bad Request error from exchange.