通过.Net应用程序发送电子邮件后Outlook RPC服务器不可用

时间:2015-01-16 08:48:30

标签: c# email outlook

我刚刚开始研究.Net和Office应用程序之间的互操作性,特别是Outlook。我已经设法通过Outlook发送电子邮件但由于某种原因,在我发送电子邮件(如果outlook尚未运行)后,Outlook服务器关闭了。这是我的代码:

private void CreateEmailItem(string subjectEmail, string toEmail, string bodyEmail)
{
    Outlook.Application oApp = new Outlook.Application();
    Outlook.MailItem oMsg =  (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
    try
    {
        Outlook.Inspector oInspector = oMsg.GetInspector;
        oMsg.Subject = subjectEmail;
        Outlook.Recipients oRecips =  (Outlook.Recipients)oMsg.Recipients;
        Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(toEmail);
        oRecip.Resolve();
        oMsg.HTMLBody = "<html><div style=font-size:16px; font-face:consolas;>" + bodyEmail + "</font></body></div></html>";
        oMsg.Send();
    }
    catch (Exception e)
    { }
    finally
    {
        //cleanup
        Marshal.FinalReleaseComObject(oMsg);
        oApp.Quit();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

因此,当我尝试调用outlook应用程序Quit()方法时会抛出错误吗?

1 个答案:

答案 0 :(得分:0)

尝试删除 Marshal.FinalReleaseComObject(oMsg); 代码行。如果使用GC.Collect方法,则无需释放基础COM对象。

另外,我建议在全局范围内声明 Application 对象。