通过 C# WinForm 发送邮件时出现奇怪的错误

本文关键字:错误 WinForm 通过 | 更新日期: 2023-09-27 18:33:03

我有这个代码用于通过C# WinForm发送邮件。

我有这个参考:

Microsoft.Office.Interop.Outlook (version 11.0)

我的代码:

string sampleSource = System.Windows.Forms.Application.StartupPath + @"'TEST.txt"; 
string sampleDisplayName = "Test";
Microsoft.Office.Interop.Outlook.Application sampleApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem sampleMessage = (Microsoft.Office.Interop.Outlook.MailItem)sampleApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
Microsoft.Office.Interop.Outlook.Recipient sampleRecipient = (Microsoft.Office.Interop.Outlook.Recipient)sampleMessage.Recipients.Add(sampleSource);
sampleRecipient.Resolve();
sampleMessage.Subject = "Test sub"
sampleMessage.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
FinalMSG = "Test msg";
sampleMessage.HTMLBody = FinalMSG;
sampleMessage.To = "MyMail@gmail.com";
int samplePosition = (int)sampleMessage.Body.Length + 1;
int sampleType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue;
Microsoft.Office.Interop.Outlook.Attachment sampleFile = sampleMessage.Attachments.Add(sampleSource, sampleType, samplePosition, sampleDisplayName);
sampleMessage.Save();
sampleMessage.Send();
sampleRecipient = null;
sampleFile = null;
sampleMessage = null;
sampleApp = null;
有时

它工作得很好,有时我收到此错误:

使用 CLSID 检索组件的 COM 类工厂 {0006F03A-0000-0000-C000-000000000046} 由于以下原因而失败 错误:80080005。

我在带有Outlook 2010...2013..2016的计算机上尝试它,同样的问题。

找不到为什么有时它有效,有时无效

谢谢

通过 C# WinForm 发送邮件时出现奇怪的错误

COM

互操作失败有几个主要原因:

  1. 未安装应用程序。这有点明显,但经常发生,值得一提。Outlook 互操作仅在安装了 Outlook 时才有效。
  2. 客户端在不同的会话中运行,或者在与主机不同的用户下运行。如果两者都只是简单的桌面应用程序,这应该不是问题,但您仍然可以使用任务管理器进行检查。
  3. COM 服务器是 32 位,而应用程序是 64 位。同样,很容易与任务管理器检查。将应用程序生成为 32 位,以允许适当的 COM 互操作工作。默认情况下,.NET 应用程序在 AnyCPU 模式下运行 - 32 位操作系统为 32 位,64 位操作系统为 64 位。因此,在 32 位计算机上一切正常,但在 64 位 Windows 上会出现位数不匹配。