我的目标是使用我的 C# 脚本自动读取 Outlook 电子邮件。上周,它正常工作,没有任何问题。自本周初以来,我收到以下错误: “由于以下错误,检索具有 CLSID 的组件的 COM 类工厂失败:80080005 服务器执行失败” 我的代码如下:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using olook = Microsoft.Office.Interop.Outlook;
namespace ReadingEmails
{
internal class Program
{
public static (string[], olook.MailItem[]) ReadMail()
{
try
{
List<string> bodyList = new List<string>();
List<olook.MailItem> emailList = new List<olook.MailItem>();
olook.Application outlookApp = new olook.Application();
olook.Folder inbox = outlookApp.Session.GetDefaultFolder(olook.OlDefaultFolders.olFolderInbox) as olook.Folder;
olook.Folders childFolders = inbox.Folders;
foreach (olook.Folder folder in childFolders)
{
//Reason behind this that if we have an outlook rule to automate moving emails into specific
//folder it will be less emails than the inbox for the script to navigate through
if (folder.Name == "testFolder")
{
//Retrieving mail items from the folder
olook.Items mailItems = folder.Items;
foreach (object item in mailItems)
{
if (item is olook.MailItem)
{
olook.MailItem mailItem = (olook.MailItem)item;
//Will only be looking at emails with subject line: Manual Incoming2
//Only looking at unread emails, otherwise we will have infinite loop
//of emails being sent
if (mailItem != null && mailItem.Subject != null && mailItem.UnRead)
{
if (mailItem.Subject.Contains("Incoming"))
{
//will not look at any emails that are replies or fowards. otherwise
//we will have infinite loop of emails being sent
try
{
if (!mailItem.Subject.Contains("RE:") || !mailItem.Subject.Contains("FW:"))
{
Console.WriteLine(DateTime.Now + " : Found Email");
bodyList.Add(mailItem.Body);
emailList.Add(mailItem);
//make email read so that we can avoid infinite loops of emails
//being sent
mailItem.UnRead = false;
}
}
catch (System.Exception ex) { Console.WriteLine(ex.Message); }
}
}
}
}
}
}
Marshal.ReleaseComObject(outlookApp);
return (bodyList.ToArray(), emailList.ToArray());
}
catch (System.Exception ex) { Console.WriteLine(ex.Message); }
return (null, null);
}
static void Main(string[] args)
{
(string[] bodyArray, olook.MailItem[] emails) = ReadMail();
Console.ReadLine();
}
}
}
我的 Microsoft.Office.Interop.Outlook.dll 被选中。我正在使用文件版本 14.0。我的虚拟机上的 Outlook 应用程序是最新的。我没有窗口更新。我已经重新启动了我的虚拟机。我不明白为什么它有效,现在它不起作用。
错误 80080005 服务器执行失败(即
CO_E_SERVER_EXEC_FAILURE
)很可能意味着您的应用程序和 Outlook 在不同的安全上下文中运行,并且 COM 系统拒绝封送调用。
确保两个应用程序都以提升的权限运行(以管理员身份运行),或者都不运行。