Search code examples
c#vstooutlook-addinoutlook-2013

How to add images from resources folder as attachment and embed into outlook mail body in C#


I have a couple of images stored in visual studio project Resources folder, and I have to load them and display on the outlook mail body. Here it is the code:

Bitmap b = new Bitmap(Properties.Resources.MyImage);
ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(b, typeof(Byte[]));
MemoryStream logo = new MemoryStream(ba);

LinkedResource companyImage = new LinkedResource(logo);
companyImage.ContentId = "companyLogo";
mailitem.HTMLBody += "<img src=\"cid:companyLogo\">";

However, it cannot display on the mail body but a ‘empty box with red x’. Can you give me some ideas?


Solution

  • Create an attachment and set the PR_ATTACH_CONTENT_ID property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x3712001F") using Attachment.PropertyAccessor.SetProperty.

    Your HTML body (MailItem.HTMLBody property) would then need to reference that image attachment through the cid:

    <img src="cid:xyz">
    

    where xyz is the value of the PR_ATTACH_CONTENT_ID property.

    Look at an existing message with OutlookSpy (I am its author) - click IMessage button.

    attachment = mailitem.Attachments.Add("c:\temp\MyPicture.jpg");
    attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1");
    mailitem.HTMLBody = "<html><body>Test image <img src=""cid:MyId1""></body></html>";