0 votes
by (520 points)
edited

Hello,

I'm using a third party control to display word documents with formatting et cetera in my WPF application.

Now I want to use the very same control to display contents of a rebex MailMessage object.

Is there a way to convert a MailMessage (with focus on embedded images and objects, character formatting and casing) to one of the following formats?

  • Microsoft Word 97-2003 format (DOC)
  • Office Open XML format (aka MS Office 2007 or .docx)
  • HTML
  • Rich Text Format (RTF)
  • Plain Text
  • WordML format
  • OpenDocument format (implemented by the OpenOffice.org office suite)
  • MHTML - web page archive format
  • Electronic Publication (EPUB)

I'll need the email message in one of the mentioned formats to display it properly.

Thank you!

Applies to: Rebex Secure Mail

1 Answer

0 votes
by (147k points)
edited
 
Best answer

MHTML is actually based on MIME format, which is what e-mail messages use as well. Converting a mail message to MHTML can be done simply by removing any extra features not needed by MHTML. For example, try the following code:

            // load the mail message (or receive it from an IMAP or POP3 server
            var mail = new MailMessage();
            mail.Load("message.eml");

            // remove signature if signed
            if (mail.IsSigned)
                mail.RemoveSignature();

            // decrypt if encrypted
            if (mail.IsEncrypted)
            {
                if (!mail.CanDecrypt)
                    throw new ApplicationException("Unable to decrypt e-mail message.");

                mail.Decrypt();
            }

            // remove attachments
            while (mail.Attachments.Count > 0)
            {
                mail.Attachments.RemoveAt(0);
            }

            // convert text body to HTML if needed
            if (!mail.HasBodyHtml)
            {
                if (mail.HasBodyText)
                    mail.BodyHtml = "<pre>" + HttpUtility.HtmlEncode(mail.BodyText) + "</pre>";
                else
                    mail.BodyHtml = "Empty";
            }

            // remove all non-HTML bodies
            for (int i = 0; i < mail.AlternateViews.Count; i++)
            {
                if (mail.AlternateViews[i].ContentType.MediaType != MediaTypeNames.Text.Html)
                {
                    mail.AlternateViews.RemoveAt(i);
                    i--;
                }
            }

            // save the message - this will produce a MHTML file
            mail.Save("message.mht");
by (520 points)
edited

Awesome, right on the spot. Thank you! :)

...