我正在尝试创建一个服务,它将作为服务器上的后台服务运行 . 该服务将在收到收件箱后立即解析电子邮件 .
我们有一个电子邮件帐户abc@organization.com . 我们使用Outlook来检查电子邮件 . 它是一项服务,因此Outlook不会一直在服务器上运行 . 我想自动为此帐户解析电子邮件 . 此帐户不是我的电子邮件帐户 . 我在C#程序中使用Microsoft.Office.Interop.outlook .
此程序正在运行,但它正在从我的电子邮件收件箱中解析电子邮件 . 我不知道如何指定特定的电子邮件来解析收件箱 . 需要知道新邮件到达时触发的事件 . 我的程序从我的收件箱中解析了一半的电子邮件,但之后它抛出了对象空引用错误 .
static void Main(string[] args)
{
Microsoft.Office.Interop.Outlook.Application myApp=new Microsoft.Office.Interop.Outlook.Application();
try
{
String Subject, Body, Createdate, Sender = null;
Microsoft.Office.Interop.Outlook.NameSpace mapinamespace = myApp.GetNamespace("MAPI");
mapinamespace.Logon(null, null,true,true);
Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapinamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
Microsoft.Office.Interop.Outlook.Accounts accounts = myApp.Session.Accounts;
try
{
foreach (Microsoft.Office.Interop.Outlook.Account account in accounts)
{
if (account.SmtpAddress == "abc@organization.com")
{
Console.Write(account);
}
else
{
Console.Write("Not found ---");
}
}
}
catch{
throw new System.Exception(string.Format("No account with amtp:{0} exists!"));}
foreach (object item in myInbox.Items)
{
try
{
var mail = item as MailItem;
if (mail != null)
{
//Creation date
Createdate = mail.CreationTime.ToString();
Console.WriteLine("CreationTime---" + Createdate);
//Grab the senders address
Sender = mail.SenderEmailAddress.ToString();
Console.WriteLine("Sender's E-mail---" + Sender);
//grab the Subject
Subject = mail.Subject.ToString();
Console.WriteLine("Subject--" + Subject);
//Grab the body
Body = mail.Body.ToString();
Console.WriteLine("Body---" + Body);
//Grab the Attachment
}
else
{
Console.Write("Error in mail---");
}
}
catch (System.Runtime.InteropServices.COMException e)
{
Console.Write(e);
}
}
}
catch (System.Runtime.InteropServices.COMException e)
{
Console.Write(e);
}
}
2 回答
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
如果要构建在服务器端上下文中运行的解决方案,则应尝试使用已为安全无人值守执行的组件 . 或者,您应该尝试找到允许至少部分代码在客户端运行的替代方法 . 如果从服务器端解决方案使用Office应用程序,则应用程序将缺少许多成功运行的必要功能 . 此外,您将承担整体解决方案稳定性的风险 .
您可以在Considerations for server-side Automation of Office文章中阅读更多相关信息 .
无论如何,看起来您对Application类的NewMailEx事件感兴趣 . 另外我建议阅读以下系列文章:
Outlook NewMail event unleashed: the challenge (NewMail, NewMailEx, ItemAdd)
Outlook NewMail event: solution options
Outlook NewMail event and Extended MAPI: C# example
Outlook NewMail unleashed: writing a working solution (C# example)
正如Eugene所提到的,您不能在服务中使用Outlook(或任何其他Office应用程序) .
对于Exchange邮箱,您可以使用EWS(基于HTTP)而不是Outlook对象模型 .
您还可以使用扩展MAPI(C或Delphi)或Redemption(任何语言)来访问服务中的Outlook数据 .