Search code examples
c#outlookoffice-interop

Release Control of Outlook


I've got an application that uses Office Interop, and it starts outlook, creates an email and attaches a file to it. My issue is that the program won't continue processing until the email is sent/closed. How do I release it, so once the below code is ran, the rest of the code will continue whilst the email is being modified by the end user? Is it as simple as running that code in a different thread or is there a better way?

 if (!Common.IsOutlookRunning())
            Process.Start("OUTLOOK.EXE");
        var outlook = new Outlook.Application();
        var message = (Outlook.MailItem)outlook.CreateItem(Outlook.OlItemType.olMailItem);
        message.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
        var recipients = (Outlook.Recipients)message.Recipients;
        var recipient = (Outlook.Recipient)recipients.Add(hire.Email);
        message.HTMLBody = "<p style=\"font-size:9.0pt;font-family:Verdana,sans-serif;color:#000066\">" +
        "Dear " + hire.ClientName + ",<br><br>";
        message.HTMLBody += "Please see the attached document. If you have any queries, please feel free to give me a call or send me an email.";
        var position = (int)message.HTMLBody.Length + 1;
        const int attachType = (int)Outlook.OlAttachmentType.olByValue;
        const string attachmentName = "Hire Docket";
        message.Attachments.Add(path, attachType, position, attachmentName);
        message.Subject = hire.Quote ? "Hire Quote" : "Hire Docket";
        message.BCC = "[email protected]";
        message.HTMLBody += "</p>" + Common.ReadSignature();
        recipient.Resolve();
        message.Display(true);

Solution

  • To fix this, I made it run in a different thread and left the main thread to do other things.

    var thread = new Thread(() => Method(Parameters));
    thread.Start();