Search code examples
outlookvstooutlook-redemption

Save complete email, body and header, as PDF


I want to save complete mail as PDF.

I found code below in stackoverflow 1. It saves the mailitem body and not the header (such as sender, recipient, subject).

I tried to manipulate the Word.Document to add the header info manually (in the code below I just use minimal changes for testing purposes) but it seems to be readonly. I also thought of "Print as PDF" using the Outlook print functionality, but found no way to get it triggered from my Outlook VSTO solution.

using Word = Microsoft.Office.Interop.Word;

private void SaveMailAsPDF(Outlook.MailItem _mailitem)
        {
            //source: https://stackoverflow.com/questions/26421252/save-outlook-mailitem-body-as-pdf
            Outlook.MailItem mi = _mailitem;
            mi.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
string datetimeReceived = mi.ReceivedTime.ToString("yyyyMMdd-Hmmss");
            string fullPath = @"C:\Users\al\Documents\OutlookMailsTest\" + datetimeReceived + "Test.pdf";

            Word.Document doc = mi.GetInspector.WordEditor;
            //doc.Paragraphs.Add();
            //doc.Paragraphs.Add();
            //Word.Range rng = doc.Range(0, 0);
            //rng.Text = "New Text";
            doc.SaveAs2(fullPath, FileFormat: Word.WdSaveFormat.wdFormatPDF);
        }

Solution

  • Try to save in the MHTML format (it preserves the embedded pictures and includes the headers) using MailItem.SaveAs, then open the MHTML file using Word object model and save it as a PDF file.