C# 使用Outlook interop发送电子邮件时出现COM异常
我正在尝试使用以下代码在我的WPF应用程序中发送电子邮件C# 使用Outlook interop发送电子邮件时出现COM异常,c#,outlook,com,office-interop,C#,Outlook,Com,Office Interop,我正在尝试使用以下代码在我的WPF应用程序中发送电子邮件 private static void ApplicationDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { //Log the exception details here: e.Handled = true; SendEmail(); } private void S
private static void ApplicationDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
//Log the exception details here:
e.Handled = true;
SendEmail();
}
private void SendEmail()
{
try
{
app = new Outlook.Application();
ns = app.GetNamespace("mapi");
ns.Logon(Missing.Value, Missing.Value, true, true);
msg = (Outlook.MailItem)app.CreateItem(Outlook.OlItemType.olMailItem);
...
...
...
await Task.Run(() =>
{
(msg as Outlook._MailItem).Send();
AppLogger.Log.Info("Email sent successfully!.");
});
}
catch(Exception ex)
{
//Handle exception here.
}
finally
{
if (ns != null)
{
ns.Logoff();
}
msg = null;
ns = null;
app = null;
}
}
此代码似乎工作正常,在其他环境中部署时会发送电子邮件。
但是今天,当我通过VisuaStudio在我的机器上运行代码时,我在这一行遇到了以下错误-->(msg as Outlook.\u MailItem).Send()代码>
异常:[System.Runtime.InteropServices.InvalidComObject异常:
无法删除已与其基础RCW分离的COM对象
COM对象在另一个服务器上仍在使用时被释放
线
想知道为什么我会出现这个错误,我能做些什么来解决它
感谢您的帮助。首先,此错误表示您的应用程序已释放COM对象。
其次,绝对没有理由在单独的线程中运行MailItem.Send
。Send
方法无论如何都是异步的。Outlook只是将邮件标记为已准备好提交,并将其交给传输提供程序,传输提供程序将其异步发送。首先,错误意味着COM对象已被重新发布由您的应用程序启动。
其次,绝对没有理由在单独的线程中运行MailItem.Send
。Send
方法无论如何都是异步的。Outlook只是将邮件标记为可以提交,并将其交给传输提供程序,由传输提供程序异步发送。是否需要作为任务运行?如果只是运行,您看到了吗同步运行?COM喜欢多线程。如果你必须这样做,你需要thread.SetApartmentState(System.Threading.ApartmentState.STA);是否需要作为任务运行?你看到如果运行只是同步运行吗?COM喜欢多线程。如果你必须这样做,你需要thread.SetApartmentState(System.Threading.ApartmentState.STA);