How to open .eml files using Outlook MAPI in C #?

I have a C # application that reads .msg files and extracts body and attachments. But when I try to download the .eml file, the application crashes. I upload files as follows:

MailItem mailItem = (MailItem)outlookApp.CreateItemFromTemplate(msgFileName); mailItem.SaveAs(fullFilename, OlSaveAsType.olHTML); // save body in html format for(int i = 0; i < mailItem.Attachments.Count; i++) mailItem.Attachments[i].SaveAsFile(filename); // save attachments 

This works fine with .msg files, but it does not work for .eml files. I do not understand why .eml files do not work, because I can open .eml files in Outlook 2010.

How to download .eml files using Outlook Primary Build Interaction ?

+6
source share
4 answers

CreateItemFromTemplate only works with MSG / OFT files. For EML files, you need to either explicitly parse the file in your code, or use a third-party library (for example, Atonement):

The following code will create the MSG file and import the EML file into it using the Redemption ( RDOSession object):

  set Session = CreateObject("Redemption.RDOSession") Session.MAPIOBJECT = outlookApp.Session.MAPIOBJECT set Msg = Session.CreateMessageFromMsgFile("C:\Temp\temp.msg") Msg.Import "C:\Temp\test.eml", 1024 Msg.Save MsgBox Msg.Subject 

Then you can use the message ( RDOMail ) to get various properties to it (Subject, Body, etc.)

+5
source

To create MailItem from an .eml file, you can use the following two steps: first you open an instance of the lookup process, and then create MailItem using the Outlook API.

  string file = @"C:\TestEML\EmlMail.eml"; System.Diagnostics.Process.Start(file); Outlook.Application POfficeApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application"); // note that it returns an exception if Outlook is not running Outlook.MailItem POfficeItem = (Outlook.MailItem)POfficeApp.ActiveInspector().CurrentItem; // now pOfficeItem is the COM object that represents your .eml file 
0
source

Although Outlook can open EML files , it cannot do this programmatically only with VBA. So I created this VBA macro that goes through some folder and opens every EML file with SHELL EXEC . This can take several milliseconds until Outlook opens the EML file, so VBA waits until something opens in ActiveInspector. Finally, this letter is copied to some selected folder, and (if successful) the original EML file is deleted.

See my full answer (and code) here: fooobar.com/questions/888297 / ...

0
source

Source: https://habr.com/ru/post/888295/


All Articles