Search code examples
c#rtfoutlook-2010mailitem

Editing MailItem.RTFBody through encoding


I've had some success encoding the RTFbody from a MailItem using UTF8Encoding. I'm able to compose a new email, do all the new-email stuff and click send. Upon hitting send, I append the email with a tag that is also added to the categories. This all works and all through the RTFBbody.

The problem comes when I reply to RTF emails, which, for testing purposes, are just the emails I sent to my lonesome self. When I send the reply email and new tags were added, I remove the old tags first and then add the new tags. When I set the RTFBody in the reply email with the edited string that contains the new tags, I get a "not enough memory or disk space" error. This doesn't happen when I just remove the tags with the same function.

Bellow is the code I'm using:

private void ChangeRTFBody(string replaceThis, string replaceWith)
{
    byte[] rtfBytes = Globals.ThisAddIn.email.RTFBody as byte[];
    System.Text.Encoding encoding = new System.Text.UTF8Encoding();
    string rtfString = encoding.GetString(rtfBytes);

    rtfString = rtfString.Replace(replaceThis, replaceWith);

    rtfBytes = encoding.GetBytes(rtfString);
    Globals.ThisAddIn.email.RTFBody = rtfBytes; < // The error is here only on 
                                                  // reply and only when I replace 
                                                  // with new tags
}

These are the calls I make:

Delete old tag: ChangeRTFBody(lastTag, "");

Add new tag: ChangeRTFBody("}}\0", newTag + "}}\0");

Like I said, This works when I create a new email and send it, but not when I try to reply to the same email. It also seems that the size of the byte[] almost doubles after the delete. When I check it during the Delete it's at about 15k bytes and when I check during the Add it jumps to over 30k bytes. When I try to add the newly inflated byte[] to the rtfBody is when I get the error.

Thanks for any help and tips and sorry about all the reading.


Solution

  • I had the same problem and came across what I think is an easier way to replace text in a outlook rtf body by using the Word.Document object model. You will need to add reference of Microsoft.Office.Interop.Word to your project first.

    then add using

    using Word = Microsoft.Office.Interop.Word;
    

    then your code would look like

    Word.Document doc = Inspector.WordEditor as Word.Document;
    
    //body text
    string text = doc.Content.Text;
    
    //find text location
    int textLocation = text.IndexOf(replaceThis);
    
    if(textLocation > -1){
         //get range
         int textLocationEnd = textLocation + replaceThis.Length;
    
         //init range
         Word.Range myRange = doc.Range(textLocation , textLocationEnd);
    
         //replace text
         myRange.Text = replaceWith
    }