【发布时间】: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/…