Search code examples
c#outlook-addin

Include image from website in mailitem.HTMLBody


I am currently developing an add-in for Microsoft Outlook that adds an image right before the tag of an html body. This image is located on a remote server so the source of the image tag is http://someserver.com/image.jpg

This works exactly as expected on a fresh e-mail ( aka a new e-mail ) However when a user clicks reply, or forward for some reason the image source gets changed to cid:image001.jpg and the actual image source gets put in the alt tag.

I am altering the body on the send event as I want the image to be added after the e-mail is finished being written.

The code that is run at the send event

void OutlookApplication_ItemSend(object Item, ref bool Cancel)
    {

        if (Item is Outlook.MailItem)
        {
            Outlook.MailItem mailItem = (Outlook.MailItem)Item;

            string image = "<img src='http://someserver.com/attach.jpg' width=\"100\" height=\"225\" alt=\"\" />";
            string body = mailItem.HTMLBody;

            body = body.Replace("</body>", image + "</body>");

            mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
            mailItem.HTMLBody = body;
        }
    }

Solution

  • So I found a way to do it that works. What I ended up having to do was create a new mailItem, copy the existing mailitem into it, modify and send that item and cancel the original. The following code shows how I did it:

    void OutlookApplication_ItemSend(object Item, ref bool Cancel)
        {
    
            if (Item is Outlook.MailItem)
            {
                Outlook.Inspector currInspector;
                currInspector = outlookApplication.ActiveInspector();
                Outlook.MailItem oldMailItem = (Outlook.MailItem)Item;
                Outlook.MailItem mailItem = oldMailItem.Copy();
                string image = "<img src='http://someserver.com/attach.jpg' width=\"1\" height=\"1\" alt=\"\" />";
                string body = mailItem.HTMLBody;
    
                body = body.Replace("</body>", image+"</body>");
    
                mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
                mailItem.HTMLBody = body;
    
                mailItem.Send();
                Cancel = true;
                currInspector.Close(Outlook.OlInspectorClose.olDiscard);
            }
        }