【问题标题】:Strange error in sending the mail through C# WinForm通过 C# WinForm 发送邮件的奇怪错误
【发布时间】:2016-05-11 10:05:55
【问题描述】:

我有这段代码用于通过 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 的电脑上试了一下,同样的问题。

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

谢谢

【问题讨论】:

  • 出于好奇,您为什么使用 Outlook COM 而不仅仅是 System.Net.Mail 库?
  • 如果您不介意使用 System.Net.Mail,可以参考以下线程:stackoverflow.com/questions/35108461/…
  • 好的,我试试这个及其工作。但是如何将文件添加到此方法中?以及如何在不打开 Outlook 的情况下发送邮件?
  • @Gold:您可以通过 SMTP 发送,您可以参考此代码示例:msdn.microsoft.com/en-us/library/…

标签: c# winforms email


【解决方案1】:

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

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

【讨论】:

  • 感谢您的帮助,我尝试了所有这些 - 但仍然是同样的问题
猜你喜欢
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2014-03-16
相关资源
最近更新 更多