Convert MSG to PDF in C# and extract attachments from MSG files

During Conversion of an email, I’d like to keep the original attachment file type instead of converting each attachment to different file type.

E.g. I have a .msg file with a .docx attachment and I want to convert the MSG to a PDF but I want to save the .docx attachment in its original format and not convert to PDF. Is there a way to do this with the Conversion API?

1 Like

We are investigating this scenario. Your investigation ticket ID is CONVERSIONNET-5046. You’ll be notified in case of any update.

@agilelaw

Yes, it is possible. The key point is to use Convert() method with ConvertOptionsProvider overload. It is called for each converted document (the MSG itself and for each attachment). By this you can set different ConvertOptions depending on the document type to be converted. Here is a sample code snippet:

    var index = 1;
    GroupDocs.Conversion.Options.Load.LoadOptions LoadOptionsProvider(FileType sourceType)
    {
        if (sourceType == EmailFileType.Eml)
        {
            return new GroupDocs.Conversion.Options.Load.EmailLoadOptions
            {
                ConvertOwned = true,
                ConvertOwner = true,
                Depth = 2
            };
        }
        return null;
    }
    Stream ConvertedStreamProvider(FileType targetType)
    {
        string outputFile = $"converted-{index++}.{targetType.Extension}";
        return new FileStream(outputFile, FileMode.Create);
    }
    ConvertOptions ConvertOptionsProvider(string sourceDocumentName, FileType sourceType)
    {
        if (sourceType == EmailFileType.Eml)
        {
            return new PdfConvertOptions();
        }
        if (sourceType == WordProcessingFileType.Docx)
        {
            return new WordProcessingConvertOptions();
        }
        return new ImageConvertOptions();
    }

    using (var converter = new Converter("sample_with_attachments.eml", LoadOptionsProvider))
    {
        converter.Convert(ConvertedStreamProvider, ConvertOptionsProvider);
    }

Thank you. Does that work with unsupported file types too? E.g. a zip file or a video file?

1 Like

@agilelaw

We’re further investigating it.

@agilelaw

No, it will not work for unsupported file formats.