How to convert outlook email (.msg) to pdf c# ?

don bradman 621 Reputation points
2023-05-09T07:35:53.6466667+00:00

Are there any free libraries using which I can convert outlook emails i.e. .msg files to pdf in my WPF c# app?

I've tried using PDFSharp like below but the data is not showing properly at all. The email body contains tables and text and sometimes it may even contain images, so please help

		public static void GenPDF()
		{
			// Load the Outlook email
			
			Application outlookApp = new Application();
			MailItem mailItem = (MailItem)outlookApp.CreateItemFromTemplate(@"C:\Users\yy\Desktop\Re payment release 222.msg");
			
			// Create a new PDF document
			PdfDocument document = new PdfDocument();

			// Create a new PDF page
			PdfPage page = document.AddPage();

			// Create a new PDF graphics object
			XGraphics gfx = XGraphics.FromPdfPage(page);

			// Add the email content to the document
			gfx.DrawString(mailItem.Body, new XFont("Arial", 12), XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.TopLeft);

			// Save the document
			document.Save(@"D:\output.pdf");

		}
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,762 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,858 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Hui Liu-MSFT 48,506 Reputation points Microsoft Vendor
    2023-05-16T06:32:37.17+00:00

    Hi,@don bradman. According to my tests, the code below works fine. You could refer to the following code to convert the .msg file to a word file and then to pdf.

    xaml:

    
     <Button Content="convert" Width="100" Height="50" Click="Button_Click"/>
    
    

    Codebedhind:

    
    using Microsoft.Office.Interop.Word;
    using System;
    using System.Runtime.InteropServices;
    using System.Windows;
    using Application = Microsoft.Office.Interop.Word.Application;
    using Outlook = Microsoft.Office.Interop.Outlook;
    using Window = System.Windows.Window;
    using Word = Microsoft.Office.Interop.Word;
    namespace ConverterMSGToPDF
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            public void ConvertMsgToWord(string msgFilePath, string outputFilePath)
            {
                Application wordApp = new Application();
    
                wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                wordApp.Visible = false;
    
                try
                {
                    Outlook.Application outlookApp = new Outlook.Application();
                    Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.Session.OpenSharedItem(msgFilePath);
    
                    Document document = wordApp.Documents.Add();
                    Range range = document.Range();
                    range.InsertAfter(mailItem.Body);
    
                    document.SaveAs(outputFilePath, Word.WdSaveFormat.wdFormatDocumentDefault);
                   
                    document.Close();
    
                    Marshal.ReleaseComObject(document);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An error occurred: " + ex.Message);
                }
                finally
                {
                    wordApp.Quit();
                    Marshal.ReleaseComObject(wordApp);
                }
            }
          
            public void ConvertWordToPdf(string wordFilePath, string outputFilePath)
            {
                Word.Application wordApp = new Word.Application();
    
                Word.Document document = wordApp.Documents.Open(wordFilePath);
    
                document.SaveAs2(outputFilePath, Word.WdSaveFormat.wdFormatPDF);
    
                document.Close();
                wordApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(document);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
    
                string msgFilePath = "C:\\Users\\Administrator\\Desktop\\sample.msg";
                string wordFilePath = "C:\\Users\\Administrator\\Desktop\\output.docx";
                ConvertMsgToWord(msgFilePath, wordFilePath);
    
                string outputFilePath = "C:\\Users\\Administrator\\Desktop\\output.pdf";
                ConvertWordToPdf(wordFilePath, outputFilePath);
    
            }
        }
    }
    
    
    

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

  2. Castorix31 84,546 Reputation points
    2023-05-17T14:58:14.4266667+00:00

    This quick test works on my configuration (Office 2016, Windows 10 22H2, with a .msg with 2 images inside) :

                    string sMsgFile = @"E:\Sources\OpenMSG\Test_Images.msg";
                    string sPDFFile = @"E:\Sources\OpenMSG\Test_Images.pdf";
                    var olApp = new Microsoft.Office.Interop.Outlook.Application();
                    var oMI = olApp.Session.OpenSharedItem(sMsgFile) as Microsoft.Office.Interop.Outlook.MailItem;               
    
                    var oInspector = oMI.GetInspector;
                    bool bMail = oInspector.IsWordMail();
                    var et = oInspector.EditorType;
                    if (bMail && et == OlEditorType.olEditorWord)
                    {
                        oInspector.Activate();
                        var oDoc = oInspector.WordEditor;
                        oDoc.ExportAsFixedFormat(sPDFFile, 17);
                        Marshal.ReleaseComObject(oDoc);
                    }
                    Marshal.ReleaseComObject(oInspector);
                    Marshal.ReleaseComObject(oMI);
                    olApp.Quit();    
    

  3. Mickey7877-7284 6 Reputation points
    2024-08-29T07:36:02.09+00:00

    You can try to use Spire.Email in conjunction with the Spire.Doc library to convert .msg files to pdf in C#. Refer to the code below:

    MailMessage mail = MailMessage.Load("sample.msg");
    string htmlBody = mail.BodyHtml;
    Document doc = new Document();
    Section section = doc.AddSection();
    Paragraph p = section.AddParagraph();
    p.AppendHTML(htmlBody);
    string result = "result.pdf";
    doc.SaveToFile(result, FileFormat.PDF);
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.