Search code examples
c#textoutlookinteropmsg

Converting .MSG files to .TXT; Should I use Microsoft.Interop Outlook?


I'm trying to do a conversion from .msg files into .txt. I have two questions.

1)I've been investigating and found the Microsoft.Interop Outlook package and there is a way where I can extract the bodyHTML, To, Sent Date, and a few other properties but I feel as if this is a very manual process because I have to trim out all the html tags such as < br>, &nbsp, a href etc...

Here is my current code...

MailItem mailItem = outlookApp.Session.OpenSharedItem(item) as MailItem;
TextFile textFile = new TextFile(); //collection of properties I am interested in
textFile.To = mailItem.To;
textFile.Subject = mailItem.Subject;
textFile.Sent = mailItem.SentOn.ToString();
textFile.Name = Path.GetFileNameWithoutExtension(item);
var atttach = mailItem.Attachments;  //Really just want the names 
textFile.Body = RemoveStuff(mailItem.HTMLBody); //manually removing all html tags
textFiles.Add(textFile);
Marshal.ReleaseComObject(mailItem);

Does anyone know if there is a more effective way to do this in C# or a way using Interop that I am not aware of?

2)If I go the interop route, is there a way I can bypass the popup in Outlook asking if I can allow access to Outlook? Seems inefficient if my goal is to create a converter.

Any help is greatly appreciated.

Thanks!


Solution

  • Firstly, why are you using HTMLBody property instead of the plain text Body?

    Secondly, you can use MailItem.SaveAs(..., olTxt) to save the message as a text file. Or do you mean something else by txt file?

    The security prompt is raised by Outlook if your antivirus app is not up to date. If you cannot control the environment where your code runs, Extended MAPI (C++ or Delphi only) or a wrapper like Redemption (any language - I am its author) are pretty much your only option. See http://www.outlookcode.com/article.aspx?id=52 for more details.

    In Redemption, you can have something like the following:

    using Redemption;
    ...
    RDOSession session = new RDOSession();
    RDOMail msg = session.GetMessageFromMsgFile(TheFileName);
    msg.SaveAs(TxtFileName, rdoSaveAsType.olTXT);