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

2

2

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;
Lansing answered 27/7, 2011 at 17:42 Comment(1)
Why are you using a Regex? Is it to figure out if it's a msg file? You can use the Path class. Try if(Path.GetExtension(fl) == ".msg")Cathleencathlene
C
7

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

Cathleencathlene answered 27/7, 2011 at 17:53 Comment(1)
Exactly what I was looking for, but would not of known how to get there. New to c# from Java, thanks. using the app.session... was not what i was think and going to look into what it actually does. Thanks. Using regex to keep system flexible because using different checks for different files. ie. pics, docs, pdfs... just storing in a app.config to change in one place. Thanks.Lansing
D
1

I used this NuGet package: https://www.nuget.org/packages/MSGReader/

Seems to work fine. I prefer it to the MS OutlookApi library because it doesn't require Outlook to be installed.

I appreciate that it won't create instances of MailItem, as you have asked for in your question - but it will enable you to extract save the individual attachments and the body...

Diathermic answered 29/10, 2014 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.