Search code examples
exchangewebservices

How to retrieve images embedded in an email body using EWS


I am using EWS in C# to query emails in my mailbox. I am able to get the email body message. I want to know how can I get the images embedded int the email.

Here is an example of email body. I want to download the image "cid:image002.jpg@01CFD899.89339A10", how can I do that?

<body lang="EN-US" link="#0563C1" vlink="#954F72">
<div class="WordSection1">
<p class="MsoNormal">Solid wood dining table with 6 chairs (2 captain chairs, 4 armless).&nbsp; Great condition.<o:p></o:p></p>
<p class="MsoNormal"><o:p>&nbsp;</o:p></p>
<p class="MsoNormal"><o:p>&nbsp;</o:p></p>
<p class="MsoNormal"><img width="469" height="287" id="Picture_x0020_1" src="cid:image001.jpg@01CFD899.89339A10">
<o:p></o:p></p>
<p class="MsoNormal">&nbsp;<img width="212" height="313" id="Picture_x0020_2" src="cid:image002.jpg@01CFD899.89339A10">&nbsp;&nbsp;&nbsp;&nbsp;<img width="281" height="469" id="Picture_x0020_3" src="cid:image003.jpg@01CFD899.89339A10"><o:p>
</o:p></p>
</div>
</body>

Solution

  • The images should be in the Attachments collection so you should be able to just enumerate through the attachments collection find the matching Cid and download it. The Attachment collection won't be returned with FindItems operation so you need to make sure you use a GetItem operation on the Message to get those details eg

            ItemView view = new ItemView(100);
            view.PropertySet = new PropertySet(PropertySet.IdOnly);
            PropertySet PropSet = new PropertySet();
            PropSet.Add(ItemSchema.HasAttachments);
            PropSet.Add(ItemSchema.Body);
            PropSet.Add(ItemSchema.DisplayTo);
            PropSet.Add(ItemSchema.IsDraft);
            PropSet.Add(ItemSchema.DateTimeCreated);
            PropSet.Add(ItemSchema.DateTimeReceived);
            PropSet.Add(ItemSchema.Attachments);
            FindItemsResults<Item> findResults;
            do
            {
                findResults = service.FindItems(WellKnownFolderName.Inbox, view);
                if (findResults.Items.Count > 0)
                {
                    service.LoadPropertiesForItems(findResults.Items, PropSet);
                    foreach (var item in findResults.Items)
                    {
                        foreach (Attachment Attach in item.Attachments) {
                            if (Attach.IsInline) {
    
                                Console.WriteLine(Attach.ContentId);
                                if(Attach.ContentId == "image001.png@01CFDBF0.192F54C0"){
                                    ((FileAttachment)Attach).Load(@"c:\temp\downloadto.png");
                                }
                            }
                        }                      
                    }
                }
                view.Offset += findResults.Items.Count;
            } while (findResults.MoreAvailable);
    

    Cheers Glen