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

5

6

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?

Gann answered 17/5, 2011 at 8:53 Comment(2)
Why would you need to use MAPI to load an .eml file? Since the .eml file is just a MIME message, it should not be too hard to parse it yourself (search CodePlex for a MIME parser). Is there something specific you need out of MAPI in this regard?Botulin
This is because i have an application that splits .msg files with MAPI and i thought i dont need to do a change and open my .eml files just like i do it with .msg files without writing new code.Gann
M
8

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

Methedrine answered 20/5, 2011 at 16:26 Comment(2)
Revised version is available: Easily Retrieve Email Information from .EML Files -- Revised codeproject.com/Articles/76607/…Turnkey
@danglund The revised version looked more complex, was 3 largish .cs files instead of one (some containing irrelevant stuff), and wouldn't even compile for me.Cutaneous
E
5

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 - I am its author):

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.)

Endorsement answered 18/5, 2011 at 21:51 Comment(4)
Is it possible to import an eml without redemption?Gann
Sure, if you parse the EML file and set various MailItem object properties one at a time.Endorsement
Hi i would like to use this code but i don't have a .msg. i need a fake .msg to import an eml ? How can i import/open an eml directly ?Trulatrull
The script above creates a temporary MSG file (you can delete it later or call Msg.Delete when you are done) so that it will have something to import an EML file into. MAPI or Outlook Object Model do not natively work with EML files - you need to have either a message in one of Outlook folders, or an MSG file.Endorsement
C
0

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
Centaurus answered 29/5, 2015 at 8:26 Comment(1)
This would cause the EML file to be displayed, which might not be what the OP wants.Endorsement
A
0

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://mcmap.net/q/1770745/-convert-multiple-eml-files-to-single-pst-in-c

Aboveground answered 17/11, 2015 at 16:2 Comment(0)
C
0

Assuming outlook is installed...

for only a msg file, when outlook is running/already open, you can use OpenSharedItem

Microsoft.Office.Interop.Outlook.Application appOutlook = new Microsoft.Office.Interop.Outlook.Application();
var myMailItem = appOutlook.Session.OpenSharedItem(strPathToSavedEmailFile) as Microsoft.Office.Interop.Outlook.MailItem;

for eml file or msg file (Outlook will open and pop up):

var strPathToSavedEmailFile=@"C:\temp\mail.eml";
//Microsoft.Win32 namespace to get path from registry
var strPathToOutlook=Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths\outlook.exe").GetValue("").ToString();
//var strPathToOutlook=@"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE";

string strOutlookArgs;
if(Path.GetExtension(strPathToSavedEmailFile)==".eml")
{
  strOutlookArgs =  @"/eml "+strPathToSavedEmailFile;  // eml is an undocumented outlook switch to open .eml files
}else
    {
     strOutlookArgs =   @"/f "+strPathToSavedEmailFile;
    }

Process p = new System.Diagnostics.Process();
p.StartInfo = new ProcessStartInfo()
{
    CreateNoWindow = false,
    FileName = strPathToOutlook, 
    Arguments = strOutlookArgs
};
p.Start();

//Wait for Outlook to open the file
Task.Delay(TimeSpan.FromSeconds(5)).GetAwaiter().GetResult();

Microsoft.Office.Interop.Outlook.Application appOutlook = new Microsoft.Office.Interop.Outlook.Application();
//Microsoft.Office.Interop.Outlook.MailItem myMailItem  = (Microsoft.Office.Interop.Outlook.MailItem)appOutlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
var myMailItem = (Microsoft.Office.Interop.Outlook.MailItem)appOutlook.ActiveInspector().CurrentItem;

//Get the Email Address of the Sender from the Mailitem 
string strSenderEmail=string.Empty;
if(myMailItem.SenderEmailType == "EX"){
    strSenderEmail=myMailItem.Sender.GetExchangeUser().PrimarySmtpAddress;
}else{
    strSenderEmail=myMailItem.SenderEmailAddress;
}

//Get the Email Addresses of the To, CC, and BCC recipients from the Mailitem   
var strToAddresses = string.Empty;
var strCcAddresses= string.Empty;
var strBccAddresses = string.Empty;
foreach(Microsoft.Office.Interop.Outlook.Recipient recip in myMailItem.Recipients)
    {
    const string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
    Microsoft.Office.Interop.Outlook.PropertyAccessor pa = recip.PropertyAccessor; 
    string eAddress = pa.GetProperty(PR_SMTP_ADDRESS).ToString(); 
    if(recip.Type ==1)
        {
        if(strToAddresses == string.Empty)
            {
            strToAddresses = eAddress;
            }else
                {
                strToAddresses = strToAddresses +","+eAddress;
                }
        };
    if(recip.Type ==2)
        {
        if(strCcAddresses == string.Empty)
            {
            strCcAddresses = eAddress;
            }else
                {
                strCcAddresses = strCcAddresses +","+eAddress;
                }       
        };
    if(recip.Type ==3)
        {
        if(strBccAddresses == string.Empty)
            {
            strBccAddresses = eAddress;
            }else
                {
                strBccAddresses = strBccAddresses +","+eAddress;
                }       
        };
    }
Console.WriteLine(strToAddresses);
Console.WriteLine(strCcAddresses);
Console.WriteLine(strBccAddresses);
foreach(Microsoft.Office.Interop.Outlook.Attachment mailAttachment in myMailItem.Attachments){
    Console.WriteLine(mailAttachment.FileName);
}
Console.WriteLine(myMailItem.Subject);
Console.WriteLine(myMailItem.Body);
Congius answered 24/12, 2022 at 23:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.