✖

Просмотр и конвертация почтового сообщения в .NET приложении

Категория: Imaging; .NET

1 октября 2026

.EML файл - это файл в котором хранится одиночное электронное письмо в формате RFC 5322. Формат .EML поддерживается всеми программами для работы с электронной почтой.

.MSG файл - это файл в котором хранится почтовое сообщение созданное в программе Microsoft Outlook.

Любое современное почтовое сообщение хранится в 2х форматах: текстовом и HTML, то есть для просмотра почтового сообщения нужно просмотреть либо текстовый файл, либо HTML страничку. И конечно же в современном мире основным форматом является HTML, а текстовая версия используется как вспомогательная. Соответственно для рендеринга почтового сообщения требуется рендеринг HTML.


VintaSoft Imaging .NET SDK 15.2 и более поздние версии позволяет работать с .EML и .MSG файлами, то есть можно:

Для работы с .EML-файлом нужны следующие nuget-пакеты: Vintasoft.Shared, Vintasoft.Imaging.
Для работы с .MSG-файлом нужны следующие nuget-пакеты: Vintasoft.Shared, Vintasoft.Imaging, OpenMcdf.


Вот C# код, который демонстрирует как получить информацию о файле электронной почты:
/// <summary>
/// Extracts metadata from Email (.msg, .eml) document.
/// </summary>
/// <param name="emailFilePath">Path to a source Email file.</param>
public static void ExtractMetadataFromEmail(string emailFilePath)
{
    // create image collection
    Vintasoft.Imaging.ImageCollection images = new Vintasoft.Imaging.ImageCollection();
    try
    {
        // open Email file
        images.Add(emailFilePath);

        // create metadata for Email document
        Vintasoft.Imaging.Metadata.EmailDocumentMetadata emailMetadata =
         (Vintasoft.Imaging.Metadata.EmailDocumentMetadata)images[0].SourceInfo.Decoder.GetDocumentMetadata();

        // names of attachments
        if (emailMetadata.AttachmentNames.Length > 0)
        {
            System.Console.WriteLine("Attachments:");
            foreach (System.Uri attachmentName in emailMetadata.AttachmentNames)
            {
                System.Console.Write(attachmentName);
                using (System.IO.Stream attachmentStream = emailMetadata.CreateAttachmentStream(attachmentName))
                    System.Console.Write(" (" + attachmentStream.Length + " bytes)");
                System.Console.WriteLine();
            }
            System.Console.WriteLine();
        }

        // headers info (From, To, Subject...)
        System.Console.WriteLine("Headers:");
        foreach (Vintasoft.Imaging.Codecs.Decoders.EmailHeaderInfo headerInfo in emailMetadata.HeadersInfo)
        {
            System.Console.WriteLine(headerInfo.Name + ": " + headerInfo.Value.ToString());
        }
    }
    finally
    {
        images.ClearAndDisposeItems();
    }
}


Вот C# код, который демонстрирует как извлечь текст из файла электронной почты:
/// <summary>
/// Extracts the text from Email (.msg, .eml) document.
/// </summary>
/// <param name="emailFileName">Name of the Email file.</param>
public static void ExtractTextFromEmail(string emailFileName)
{
    using (Vintasoft.Imaging.ImageCollection images = new Vintasoft.Imaging.ImageCollection())
    {
        // open Email document
        images.Add(emailFileName);

        try
        {
            // page number
            int pageNumber = 1;
            
            // for each page of HTML dcoument
            foreach (Vintasoft.Imaging.VintasoftImage image in images)
            {
                // write page number
                System.Console.WriteLine("\tPage Number: {0}", pageNumber++);
                System.Console.WriteLine();
                System.Console.WriteLine();

                // find text region metadata
                Vintasoft.Imaging.Metadata.TextRegionMetadata textRegionMetadata =
                    image.Metadata.MetadataTree.FindChildNode<Vintasoft.Imaging.Metadata.TextRegionMetadata>();

                // if current page has text content
                if (textRegionMetadata != null)
                {
                    // get text region
                    Vintasoft.Imaging.Text.TextRegion textRegion = textRegionMetadata.GetTextRegion();
                    // write page text content
                    System.Console.Write(textRegion.TextContent);
                }

                // if page separator must be added between pages
                if (pageNumber < images.Count)
                {
                    System.Console.WriteLine();
                    System.Console.WriteLine();
                    System.Console.WriteLine();
                }
            }
        }
        finally
        {
            // clear and dispose images
            images.ClearAndDisposeItems();
        }
    }
}


Вот C# код, который демонстрирует как преобразовать файл электронной почты в TIFF-файл:
/// <summary>
/// Converts Email (.msg, .eml) document to TIFF file using ImageCollection and TiffEncoder classes.
/// </summary>
public static void ConvertEmailToTiff_ImageCollection(string emailFileName, string tiffFileName)
{
    // create image collection
    using (Vintasoft.Imaging.ImageCollection images = 
        new Vintasoft.Imaging.ImageCollection())
    {
        // layout Email document on page area: width - 210mm,  height - infinite
        Vintasoft.Imaging.Codecs.Decoders.EmailLayoutSettings layoutSettings =
            new Vintasoft.Imaging.Codecs.Decoders.EmailLayoutSettings();
        layoutSettings.PageLayoutSettings.PageSize = 
            Vintasoft.Imaging.ImageSize.FromMillimeters(210, 0, new Vintasoft.Imaging.Resolution(96));
        images.LayoutSettings.SetSettings(layoutSettings);

        // add Email document to collection
        images.Add(emailFileName);

        // render Email pages in 144 DPI
        Vintasoft.Imaging.Codecs.Decoders.RenderingSettings renderingSettings = 
            new Vintasoft.Imaging.Codecs.Decoders.RenderingSettings();
        renderingSettings.Resolution = new Vintasoft.Imaging.Resolution(144);
        images.SetRenderingSettings(renderingSettings);

        // create TiffEncoder
        using (Vintasoft.Imaging.Codecs.Encoders.TiffEncoder encoder = 
            new Vintasoft.Imaging.Codecs.Encoders.TiffEncoder(true))
        {
            // specify that TIFF encoder should use Jpeg compression for image data
            encoder.Settings.Compression = 
                Vintasoft.Imaging.Codecs.ImageFiles.Tiff.TiffCompression.Jpeg;

            // save images of image collection to TIFF file using TiffEncoder
            images.SaveSync(tiffFileName, encoder);
        }

        // dispose images
        images.ClearAndDisposeItems();
    }
}


Вот C# код, который демонстрирует как преобразовать файл электронной почты в файл HTML:
/// <summary>
/// Converts Email (.msg, .eml) document to a HTML document.
/// </summary>
/// <param name="emailFilePath">Path to a source Email file.</param>
/// <param name="htmlFilePath">Path to a result HTML file.</param>
public static void ConvertEmailToHtml(string emailFilePath, string htmlFilePath)
{
    // directory to save attachments
    string attachmentsDirectoryName = System.IO.Path.GetFileNameWithoutExtension(htmlFilePath) + ".files";

    // convert Email document to a HTML document
    Vintasoft.Imaging.Email.EmailDocumentConverter.ConvertEmailToHtml(
        emailFilePath, htmlFilePath, attachmentsDirectoryName, new Vintasoft.Imaging.Email.EmailToHtmlConverterSettings());
}


Вот C# код, который демонстрирует как преобразовать файл электронной почты в PDF-файл:
/// <summary>
/// Converts Email (.msg, .eml) document to a PDF document.
/// </summary>
/// <param name="emailFilePath">Path to a source Email file.</param>
/// <param name="pdfFilePath">Path to a result PDF file.</param>
public static void ConvertEmailToPdf(string emailFilePath, string pdfFilePath)
{
    // set default Email converter settings
    // create headers
    EmailLayoutSettings.DefaultEmailSettings.EmailConverterSettings.CreateHeader = true;
    // create attachment list in header
    EmailLayoutSettings.DefaultEmailSettings.EmailConverterSettings.CreateAttachmentsInHeader = true;

    // create image collection
    ImageCollection images = new ImageCollection();
    try
    {
        // open Email file
        images.Add(emailFilePath);

        // create PDF encoder
        using (PdfEncoder encoder = new PdfEncoder())
        {
            // create metadata for Email document
            EmailDocumentMetadata emailMetadata = (EmailDocumentMetadata)images[0].SourceInfo.Decoder.GetDocumentMetadata();

            // set subject in PDF document as the Email Subject
            string subject = emailMetadata.FindTextHeader("Subject");
            if (subject != null)
                encoder.Settings.DocumentSubject = subject;

            // set title in PDF document as the Email sender
            string sender = emailMetadata.FindTextHeader("Sender");
            if (sender != null)
                encoder.Settings.DocumentTitle = sender;

            // save images from image collection (Email document) to a PDF file
            images.SaveSync(pdfFilePath, encoder);
        }
    }
    finally
    {
        images.ClearAndDisposeItems();
    }
}


Вот C# код, который демонстрирует как преобразовать файл электронной почты в файл DOCX:
/// <summary>
/// Converts Email (.msg, .eml) document to a DOCX document.
/// </summary>
/// <param name="emailFilePath">Path to a source Email file.</param>
/// <param name="docxFilePath">Path to a result DOCX file.</param>
public static void ConvertEmailToDocx(string emailFilePath, string docxFilePath)
{
    docxFilePath = System.IO.Path.GetFullPath(docxFilePath);
    string tempHtmlFilename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(docxFilePath), 
        System.IO.Path.GetFileNameWithoutExtension(docxFilePath) + ".html");

    // directory to save attachments
    string attachmentsDirectoryName = System.IO.Path.GetFileNameWithoutExtension(docxFilePath) + ".files";

    // convert Email document to a HTML document
    Vintasoft.Imaging.Email.EmailDocumentConverter.ConvertEmailToHtml(
        emailFilePath, tempHtmlFilename, attachmentsDirectoryName, new Vintasoft.Imaging.Email.EmailToHtmlConverterSettings());

    // convert HTML document to a DOCX document
    Vintasoft.Imaging.Office.OpenXml.OpenXmlDocumentConverter.ConvertHtmlToDocx(tempHtmlFilename, docxFilePath);

    // delete temp HTML filename
    System.IO.File.Delete(tempHtmlFilename);
}