Save Attachments from Emails using C#

Save Attachments from Emails using C#

As a C# developer, you can easily extract and save the attachments from email messages programmatically. In this article, you will learn how to save attachments from emails using C#.

The following topics are discussed/covered in this article:

C# API to Save Email Attachments

For saving the attachments from MSG files, we will be using GroupDocs.Viewer for .NET API. It is a powerful document viewer API to render and display widely used file formats without installing any external software. It also enables you to quickly view popular supported file formats of WordExcelPowerPoint, Outlook emails, Project, PDF, HTML, and XML.

You can either download the DLL of the API or install it using NuGet.

Install-Package GroupDocs.Viewer

Extract and Save Attachments from Emails using C#

You can extract and save attachments from email MSG files programmatically by following the steps given below:

  • Firstly, load the MSG file using the Viewer class.
  • Then, call the Viewer.GetAttachments() method to get all the attachments of the loaded MSG file. Get the results as a collection of attachments.
  • For each attachment in the collection, save the attachment by calling the Viewer.SaveAttachment() method. Pass the attachment object and file path to save it.

The following code sample shows how to extract and save the attachments contained by email MSG file using C#.

Extract and Save Attachments from Emails using C#
Extract and save attachments from emails using C#.

Save Attachments as PDF from Emails using C#

You can save the email message attachments as PDF programmatically by following the steps given below:

  • Create an instance of the Attachment class with the attached file name and file path.
  • Initialize an instance of the MemoryStream class.
  • Load the MSG file using the Viewer class.
  • Then, call the Viewer.SaveAttachment() method and pass the Attachment and the MemoryStream object as input parameters. It will extract and save the specified attachment in the memory stream.
  • Now, load the MemoryStream object using the Viewer class.
  • Then, create an instance of the PdfViewOptions class with the output PDF file path.
  • Finally, call the Viewer.View() method to save and view the attachment as a PDF.

The following code sample shows how to save and view the attachment as a PDF from an email MSG file using C#.

Save attachments as PDF from emails using C#.

Get a Free License

You can try the API without evaluation limitations by requesting a free temporary license.

Conclusion

In this article, you have learned how to extract and save the attachments contained by email MSG file using C#. Moreover, you have seen how to save a specific attachment as a PDF programmatically. Besides, you can learn more about GroupDocs.Viewer for .NET API using the documentation. In case of any ambiguity, please feel free to contact us on the forum.

See Also