Create/Open existing msg from path to new Outlook.MailItem in c#

extraordin picture extraordin · Jul 27, 2011 · Viewed 8.6k times · Source

Hello I'd like to create a Outlook.MailItem ( I believe ) from an existing one located on disk. I have the path stored in a string, and would like to access to save the body and attachments from it.

I can't seem to figure out how to open it in c# and access it.

currently I have something along the lines of

where fl evaluates out to something like "C:\users\msgs\email.msg"

Thanks for the time

Outlook.Application app = new Outlook.Application();

        try
        {

            foreach (String fl in Directory.GetFiles(docInfo.LocalPath + _preprocessorDirectory))
            {
                if (Regex.IsMatch(fl.Trim(), _regex, RegexOptions.IgnoreCase))
                {

                   Outlook.MailItem email = new Outlook.MailItem(fl);
                   SaveAttachments(email);
                   SaveBody(email);
                }
            }
        }
        catch (Exception ex)
        {
            logger.Error("Error in Process for document " + docInfo.OriginalPath, ex);
            callback.Invoke(docInfo, false);
        }
        return false;

Answer

Christopher Currens picture Christopher Currens · Jul 27, 2011

To open an item in outlook try:

var email = (Outlook.MailItem)app.Session.OpenSharedItem(fl)

From there, you can access the Attachments property and Body property as well.

Also, as I mentioned in my comment if the Regex.IsMatch is to determing the file extension, use Path.GetExtension() instead