创建Windows服务以通过outlook com interop发送自动电子邮件

时间:2017-07-11 10:07:39

标签: c# windows email service office-interop

我正在尝试开发一个通过outlook和interop服务发送自动电子邮件并获得以下异常的应用程序。下面是有例外的代码。

 try
     {
       Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
      Microsoft.Office.Interop.Outlook.MailItem mailItem = (Outlook.MailItem)app.CreateItem(Outlook.OlItemType.olMailItem);
     mailItem.Subject = "Details of Subject";
     mailItem.To = "example@gmail.com";
     mailItem.Body = "Automated email testing"
     // mailItem.Attachments.Add(logPath);//logPath is a string holding path to the log.txt file
     mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
     mailItem.Display(false);
     mailItem.Send();
 }
catch (Exception ex)
  {
         WriteErrorLog("\n");
         WriteErrorLog(ex.Message);
         WriteErrorLog(ex.StackTrace);
}

它抛出异常:

System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType) at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType) at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj) 
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at WServiceMixInOne.ConnectionLogs.MainClass() in C:\Users\admin\documents\visual studio 2017\Projects\WServiceMixInOne\WServiceMixInOne\ConnectionLogs.cs:line 120

第120行是第一行app = new Microsoft.Office.Interop.Outlook.Application();

1 个答案:

答案 0 :(得分:0)

尝试从后台流程关闭Outlook。然后执行你的代码。