Search code examples
c#emailmessagemailkitmimekit

how modify message body - Mimekit Message


i'm using mimekit for receive and send mail for my project. I'm sending received mails with some modifications (to & from parts). And now i need to modify in body section. I'll replace specific word with asterix chars. Specific text different for every mail. Mail may be any format. You can see i found what i want but i don't know how can i replace without any error?

enter image description here


Solution

  • MimeMessage.Body is a tree structure, like MIME, so you'll have to navigate to the MimePart that contains the content that you want to modify.

    In this case, since you want to modify a text/* MimePart, it will actually be a subclass of MimePart called TextPart which is what has the .Text property (which is writable).

    I've written documentation on how to traverse the MIME structure of a message to find the part that you are looking for here: http://www.mimekit.org/docs/html/WorkingWithMessages.htm

    A very simple solution might be:

    var part = message.BodyParts.OfType<TextPart> ().FirstOrDefault ();
    part.Text = part.Text.Replace ("x", "y");
    

    But keep in mind that that logic assumes that the first text/* part you find is the one you are looking for.