Marcus K
Marcus K

Reputation: 779

How modify existing Outlook .msg file without saving to Outlook inbox using Interop

I created the following class to open an existing Outlook .msg file on disc (the 'template'), change some properties, add attachments and save it back to disc in another location. However, when I open Outlook, a new file appears in my inbox in addition to the save location! I don't want to save to any Outlook folders at all, just modify the file on disk. How do I prevent it from saving to my inbox?

public class OutlookMailManager
{
    public const string OutlookExtn = ".msg";

    public void GenerateMail(string toAddress, string fromAddress, string templateFile, string outputFile, string attachmentFile)
    {
        MailItem item = OpenMessage(templateFile);
        item.To = toAddress;
        item.SentOnBehalfOfName = fromAddress;
        item.Attachments.Add(attachmentFile);
        SaveMessage(outputFile, item);
    }

    private MailItem OpenMessage(string fileName)
    {
        var app = new Application();
        return (MailItem)app.Session.OpenSharedItem(fileName);
    }

    private void SaveMessage(string fileName, MailItem item)
    {
        fileName = Path.ChangeExtension(fileName, OutlookExtn);
        item.SaveAs(fileName, OlSaveAsType.olMSG);
    }
}

Upvotes: 0

Views: 2636

Answers (1)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66235

You can use Extended MAPI (C++ or Delphi only) and OpenIMsgOnIStg function or Redemption (any language, I am its author) - create an instance of the RDOSession object, call RDOSession.GetMessageFromMsgFile (returns an instance of the RDOMail object), modify it, call RDOMail.Save or RDOMail.SaveAs.

Upvotes: 2

Related Questions