Click here to Skip to main content
Click here to Skip to main content
Go to top

Programmatically forwarding email message with inline images

, 17 Nov 2007
Rate this:
Please Sign up or sign in to vote.
While working with VSTO 2005, I needed to programmatically forward Outlook 2007 email messages. By default, the inline images in the selected email will be added as attachments to the forwarding email. This sample code will help you to programmatically forward email messages with inline images.

Introduction

This sample code will be useful for developers who work with VSTO 2005 for programmatically forwarding Outlook 2007 email messages with inline images.

Background

When I tried to forward a email item using the MailItem.Forward() method, it did not work properly because I implemented a custom Outlook form. And, by default, the inline images in the selected message will be added as attachments to the forwarding message. Using this code, you will get a solution to forward any email message with inline images.

Using the code

In this sample application, I am following the steps below:

  1. Get the currently right-clicked email (selected email).
  2. Create a new Outlook mail (forwarding email).
  3. Assign the required properties of the selected email to the forwarding email.
  4. Trim the HTMLBody string of the selected email so that the inline body images will appear as images in the forwarding email. (Otherwise, the inline images in the selected email will be added as attachments to the forwarding email.)
  5. Open the forwarding email in a new window.

Shown below is the method ForwardSelectedMessage() that implements the above steps:

//
private void ForwardSelectedMessage()
{
    try
    {
        // create a new mail message 

        Outlook.MailItem ForwardingMessage = 
          (Outlook.MailItem)this.Application.CreateItem(
           Outlook.OlItemType.olMailItem);
        // In case you want to implement the custom outlook 
        // form you have use following commented 2 lines of code

        //Outlook.MAPIFolder templateFolder = 
        // this.Application.Session.GetDefaultFolder(
        //  Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

        //ForwardingMessage = (Outlook.MailItem)templateFolder.Items.Add(
        //                     "IPM.Note.OutlookCustomForm1");

        // get the currently selected message
        // (the message on which the user right-clicked)

        Outlook.MailItem SelectedMessage;
        SelectedMessage = (Outlook.MailItem)
          this.Application.ActiveExplorer().Selection[1];
        if (SelectedMessage != null)
        {
            if (ForwardingMessage != null)
            {
                //Subject 

                ForwardingMessage.Subject = "FW: " + SelectedMessage.Subject;
                #region Attahment 
                // Get the count of Attachments

                int attachCount = SelectedMessage.Attachments.Count;
                if (attachCount > 0)
                {
                    // loop through each attachment 

                    for (int idx = 1; idx <= attachCount; idx++)
                    {
                        string sysPath = System.IO.Path.GetTempPath();
                        if (!System.IO.Directory.Exists(sysPath + "~test"))
                        {
                            System.IO.Directory.CreateDirectory(sysPath + "~test");
                        }
                        // get attached file and save in temp folder

                        string strSourceFileName = sysPath + "~test\\" + 
                                       SelectedMessage.Attachments[idx].FileName;
                        SelectedMessage.Attachments[idx].SaveAsFile(strSourceFileName);
                        string strDisplayName = "Attachment";
                        int intPosition = 1;
                        int intAttachType = (int)Outlook.OlAttachmentType.olEmbeddeditem;
                        // Add the current attachment
                        ForwardingMessage.Attachments.Add(strSourceFileName, 
                                       intAttachType, intPosition, strDisplayName);
                    }
                }
                #endregion
                #region Body 
                string strHeader = "<p><br><br>" + 
                        "-----Original Message-----" + "<br>";
                strHeader += "From: " + SelectedMessage.SenderName + "<br>";
                strHeader += "Sent: " + SelectedMessage.SentOn.ToString() + "<br>";
                strHeader += "To: " + SelectedMessage.To + "<br>";
                strHeader += "Subject: " + SelectedMessage.Subject + "<br><br>";
                ForwardingMessage.HTMLBody = strHeader + 
                          GetTrimmedBodyText(SelectedMessage.HTMLBody);
                #endregion
                ForwardingMessage.Display(false);
            }
        }
    }
    catch (Exception ex)
    {
        if (ex.Message.ToLower().StartsWith("unable to cast com object"))
        {
            MessageBox.Show("This is not a valid message and it can not be sent.", 
                            "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("ForwardSelectedMessage - " + ex.Message, 
                    "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
#region Handling inline images in the message body 
/* by defaule the inline images in the selected message
   will be added as attachments to the new message
   the reason is in htmlbody the image src will be as follows:
   src = "cid:image001.jpg@01C82869373A65B0"
   to view inline images (and avoid image attachments) it should changed as follows:
   src = "image001.jpg"
   replace "cid" with "" (empty string) and 
   replace "image001.jpg@01C82869373A65B0" with "image001.jpg" (only file name)
*/
private string GetTrimmedBodyText(string strHTMLBody)
{
    string strTrimmedHTMLBody = strHTMLBody;
    int start = 0;
    start = strHTMLBody.IndexOf("<img", start);
    /* the following loop will check for each src attribute value for each image and 
       it will replace them only with image file name (by removing cid: and @ part)
    */
    while (start > 0)
    {
        int count = strHTMLBody.IndexOf('>', start);
        string str = strHTMLBody.Substring(start);
        string strActualImgTag = str.Substring(0, str.IndexOf(">") + 1);
        string strTrimImgTag = strActualImgTag.Replace("cid:", "");
        int intAtPosition = 0;
        intAtPosition = strTrimImgTag.IndexOf("@");
        while (intAtPosition > 0)
        {
            string strAt = 
              strTrimImgTag.Substring(strTrimImgTag.IndexOf("@"), 18);
            strTrimImgTag = strTrimImgTag.Replace(strAt, "");
            intAtPosition = strTrimImgTag.IndexOf("@");
        }
        strTrimmedHTMLBody = 
          strTrimmedHTMLBody.Replace(strActualImgTag, strTrimImgTag);
        start = strHTMLBody.IndexOf("<img", start + 1);
    }
    return strTrimmedHTMLBody;
}
#endregion
#endregion
//

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ravi Raj
Team Leader MindTree Ltd,
India India
Currently working in MindTree Ltd, Bangalore, India.

Comments and Discussions

 
QuestionDownloads images Pinmemberkiquenet.com19-Dec-13 0:16 
Questionhow can i recieve and forward the same message to a different email address PinmemberFaisal Khatri17-Aug-09 10:16 
GeneralMajor problem PinmemberMogaambo25-Jun-09 20:40 
General5 from me !!!!!!!!! PinmemberMogaambo23-Jun-09 21:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 17 Nov 2007
Article Copyright 2007 by Ravi Raj
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid