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

佐手、 提交于 2019-12-01 02:51:25

问题


I have a C# application that reads .msg files and extracts the body and the attachments. But when I try to load a .eml file the application crashes. I am loading the files like this:

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 doesn't work for .eml files. I don't understand why .eml files don't work, because I can open .eml files in Outlook 2010.

How can I load .eml files using the Outlook Primary Interop Assembly?


回答1:


Try this sample code Easily Retrieve Email Information from .EML Files




回答2:


CreateItemFromTemplate only works with the MSG/OFT files. Fot the EML files you will either need to parse the file explicitly in your code or use a third party library (such as Redemption):

The following code will create an MSG file and import an EML file into it using 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

You can then use the message (RDOMail) to access it various properties (Subject, Body, etc.)




回答3:


In order to create a MailItem from a .eml file you can use the following two steps: at first you open an outlook process instance and then you create the MailItem with 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



回答4:


Although Outlook can open EML files, there is no way to do it programatically only with VBA. So I created this VBA macro which loops through some folder and opens each EML file using SHELL EXEC. It may take a few milliseconds until Outlook opens the EML file, so the VBA waits until something is open in ActiveInspector. Finally, this email is copied into some chosen folder, and (in case of success) the original EML file is deleted.

See my complete answer (and code) here: https://stackoverflow.com/a/33761441/3606250



来源:https://stackoverflow.com/questions/6028442/how-to-open-eml-files-using-outlook-mapi-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!