2017-05-31 327 views
1

多個ID參考帖子中提到了答案: Reading Outlook Mail with C#讀取多個Outlook電子郵件在C#中

此代碼非常適用於單個帳戶,但當前的代碼的問題是,它讀取的電子郵件這是在Outlook應用程序中被設置爲第一個的默認ID。

例如,如果「[email protected]」設置爲第一個帳戶,並且「[email protected]」設置爲第二個帳戶,則它僅讀取第一個id的收件箱,即「 [email protected]」。我試着在代碼中做一些修改,但沒有奏效。以下是我的代碼:

public static void OutLookMailStart(string EmailID, string password) 
    { 
     Microsoft.Office.Interop.Outlook.Application app = null; 
     Microsoft.Office.Interop.Outlook._NameSpace ns = null; 
     Microsoft.Office.Interop.Outlook.PostItem item = null; 
     Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null; 
     Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null; 
     Microsoft.Office.Interop.Outlook.MailItem mailItem = null; 
     try 
     { 
      app = new Microsoft.Office.Interop.Outlook.Application(); 
      ns = app.GetNamespace("MAPI"); 

      ns.Logon(EmailID, password, false, true); 
      inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); 

      foreach (Object mail in inboxFolder.Items) 
      { 
       if ((mail as MailItem) != null && (mail as MailItem).UnRead == true) 
       { 
        // Email Subject 
        string Subject = (mail as MailItem).Subject.ToString(); 
        if (Subject.Contains(FileDomain)) 
        { 
         // Email Body 
         var ReplyText = ExtractReply(((mail as MailItem).Body.ToString()), FromTrimName); 
        } 
        // (mail as MailItem).UnRead = false; 
        (mail as MailItem).Save(); 
       } 
      } 
     } 
     catch (System.Exception ex) 
     { 
      throw ex; 
     } 
     finally 
     { 
      ns.Logoff(); 
      inboxFolder = null; 
      subFolder = null; 
      mailItem = null; 
      app = null; 
     }} 

任何形式的幫助將不勝感激。

+0

你是不是能夠利用任何機會交換Web服務而不是Outlook互操作? –

回答

1
public static void OutLookMailStart(string EmailID, string password) 
     { 
      Microsoft.Office.Interop.Outlook.Application app = null; 
      Microsoft.Office.Interop.Outlook._NameSpace ns = null; 
      Microsoft.Office.Interop.Outlook.PostItem item = null; 
      Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null; 
      Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null; 
      Microsoft.Office.Interop.Outlook.MailItem mailItem = null; 


      try 
      { 
       app = new Microsoft.Office.Interop.Outlook.Application(); 
       ns = app.GetNamespace("MAPI"); 

       ns.Logon(EmailID, password, true, true); 

       inboxFolder = ns.Folders[EmailID].Folders[2]; 

       foreach (Microsoft.Office.Interop.Outlook.MailItem mailItemm in inboxFolder.Items) 
       { 
        if (mailItemm.UnRead) // I only process the mail if unread 
        { 
         // Email Subject 
         Console.WriteLine("Subject : {0}", mailItemm.Subject); 
         string Subject = mailItemm.Subject; 
         if (!string.IsNullOrEmpty(Subject) && !string.IsNullOrWhiteSpace(Subject)) 
         { 
          if (Subject.Contains(FileDomain)) 
          { 


           var SenderName = mailItemm.Sender.Name; 
           //Email Body 
           Console.WriteLine("Accounts: {0}", mailItemm.Body); 




           // Read All Attachements 
           var attachments = (mailItemm as MailItem).Attachments; 
           if (attachments != null && attachments.Count > 0) 
           { 
            for (int i = 1; i <= attachments.Count; i++) 
            { 
             attachments[i].SaveAsFile(tempFolderPath + (mailItemm as MailItem).Attachments[i].FileName); 


            } 
           } 
          } 
         } 
        } 
       } 
      } 
      catch (System.Exception ex) 
      { 
       throw ex; 
      } 
      finally 
      { 
       ns.Logoff(); 
       inboxFolder = null; 
       subFolder = null; 
       mailItem = null; 
       app = null; 
      } 
     } 
+0

inboxFolder = ns.Folders [EmailID] .Folders [2]; 2意味着索引文件夾 –

0

使用ExchangeService服務

public static void Cloud_OutLookMailStart(string EmailID, string password, string StoreFilePath) 
{ 
    try 
    { 
     LogHelper.LogMessage("<----- Cloud_OutLookMailStart Start ----->"); 

     DistributionReplyEntity ObjDistributionReplyEntity = new DistributionReplyEntity(); 
     ObjDistributionReplyEntity.OutLookEmailID = EmailID; 
     ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); 
     service.Credentials = new WebCredentials(EmailID, password); 
     service.TraceEnabled = true; 
     service.TraceFlags = TraceFlags.All; 
     //service.Url = new Uri("https://IP/EWS/Exchange.asmx"); 
     service.AutodiscoverUrl(EmailID, RedirectionUrlValidationCallback); 

     Microsoft.Exchange.WebServices.Data.Folder inbox = Microsoft.Exchange.WebServices.Data.Folder.Bind(service, WellKnownFolderName.Inbox); 

     var items = service.FindItems(
     //Find Mails from Inbox of the given Mailbox 
     new FolderId(WellKnownFolderName.Inbox, new Mailbox(EmailID)), 
     //Filter criterion 
     // new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter[] { 
     // new SearchFilter.ContainsSubstring(ItemSchema.Subject, ConfigurationManager.AppSettings["ValidEmailIdentifier"].ToString()), 
     new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), 
     // }), 

     //View Size as 15 


     new ItemView(50)); 

     Console.WriteLine("Email {0}, unread Total Count{1}", EmailID, items.Count()); 


     foreach (Item item in items) 
     { 
      EmailMessage email = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId.ToString())); 

      if (!string.IsNullOrEmpty(email.Subject) && !string.IsNullOrWhiteSpace(email.Subject)) 
      { 
       var subject = email.Subject.ToString(); 
       String[] arr = subject.Split(' '); 

       String firstWord = arr[0]; 
       if (firstWord != "Undeliverable:") 
       { 
        //PROCESS EMAIL MESSAGE 
        Console.WriteLine("Subject :{0}", email.Subject); 
        // TO 
        if (email.ToRecipients.Count > 0) 
        { 

         var propertySet = new PropertySet(ItemSchema.UniqueBody); 
         EmailMessage email2 = EmailMessage.Bind(service, email.Id, propertySet); 
         EmailMessage str = (EmailMessage)email2; 
         string str1 = str.UniqueBody.Text.ToString(); 
         var EmailBody = ExtractReply(str1, ""); 
         // string ReceiverEmail = email.ReceivedBy != null?email.ReceivedBy.Address:"" ; 
         // Email Body 

         // var subjectEmail = ExtractReply(email.Body.ToString(), email.ReceivedBy.Address); 

         Console.WriteLine("Body {0}", EmailBody.ToString()); // Body 
         ObjDistributionReplyEntity.EmailBody = EmailBody; 

         string maltipleTo = string.Empty; 
         foreach (var toemailid in email.ToRecipients) 
         { 
          if (string.IsNullOrEmpty(maltipleTo)) 
          { 
           maltipleTo = toemailid.Address.ToString(); 
          } 
          else 
          { 
           maltipleTo += ";" + toemailid.Address.ToString(); 
          } 
         } 
         Console.WriteLine("TO {0}", maltipleTo.ToString()); // TO 
         ObjDistributionReplyEntity.ReplyTO = maltipleTo.ToString(); 
        } 
        // CC 
        if (email.CcRecipients.Count > 0) 
        { 
         string maltipleCC = string.Empty; 
         foreach (var ccemailid in email.CcRecipients) 
         { 

          if (string.IsNullOrEmpty(maltipleCC)) 
          { 
           maltipleCC = ccemailid.Address.ToString(); 
          } 
          else 
          { 
           maltipleCC += ";" + ccemailid.Address.ToString(); 
          } 
         } 

         Console.WriteLine("CC {0}", maltipleCC.ToString()); 
         ObjDistributionReplyEntity.ReplyCC = maltipleCC.ToString(); 
        } 
        // Form 
        if (email.Sender.Address != "") 
        { 
         ObjDistributionReplyEntity.ReplyForm = email.Sender.Address; 
        } 

        Console.WriteLine("Subject {0}", email.Subject.ToString()); // Subject 
        ObjDistributionReplyEntity.Subject = email.Subject.ToString(); 


        ObjDistributionReplyEntity.TransactionsID = 0; 
        ObjDistributionReplyEntity.IsProjectRelated = 0; 
        string Subject = email.Subject; 




        ObjDistributionReplyEntity.ReceivedTime = email.DateTimeReceived; 

        var getSharePointFileUrl = GetAttachmentsFromEmail(service, item.Id, StoreFilePath, ObjDistributionReplyEntity.TransactionsID); 


        email.IsRead = true; 
        email.Update(ConflictResolutionMode.AlwaysOverwrite); 
       } 
      } 
     } 

     LogHelper.LogMessage("<----- Cloud_OutLookMailStart Start ----->"); 

    } 
    catch (Exception ex) 
    { 
     LogHelper.LogError("OutLookMailStart -> Cloud_OutLookMailStart Exception"); 
     LogHelper.LogError("Exception Message :" + ex.Message); 
     if (ex.InnerException != null) 
     { 
      LogHelper.LogError("Exception InnerException :" + ex.InnerException); 
     } 
     LogHelper.LogError("Exception StackTrace :" + ex.StackTrace); 
     LogHelper.LogError("OutLookMailStart -> Cloud_OutLookMailStart Exception"); 
    } 
} 

公共靜態字符串GetAttachmentsFromEmail(ExchangeService服務,項目Id的itemId,串StoreFilePath,Int64的TransactionsID) {

try 
    { 
     LogHelper.LogMessage("<----- GetAttachmentsFromEmail Start ----->"); 





     // Bind to an existing message item and retrieve the attachments collection. 
     // This method results in an GetItem call to EWS. 
     EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments)); 
     List<ResponseMessage> ObjResponseMessage = new List<ResponseMessage>(); 
     // Iterate through the attachments collection and load each attachment. 
     foreach (Attachment attachment in message.Attachments) 
     { 
      if (attachment is FileAttachment) 
      { 
       FileAttachment fileAttachment = attachment as FileAttachment; 

       // Load the attachment into a file. 
       // This call results in a GetAttachment call to EWS. 

       fileAttachment.Load(StoreFilePath + fileAttachment.Name); 


       string FileName = fileAttachment.Name; 





       LogHelper.LogMessage("OutLookMailStart In attachments File Name :" + FileName); 


       Console.WriteLine("File attachment name: " + fileAttachment.Name); 
      } 
      else // Attachment is an item attachment. 
      { 
       ItemAttachment itemAttachment = attachment as ItemAttachment; 

       // Load attachment into memory and write out the subject. 
       // This does not save the file like it does with a file attachment. 
       // This call results in a GetAttachment call to EWS. 
       itemAttachment.Load(); 

       Console.WriteLine("Item attachment name: " + itemAttachment.Name); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     LogHelper.LogError("OutLookMailStart -> GetAttachmentsFromEmail Exception"); 
     LogHelper.LogError("Exception Message :" + ex.Message); 
     if (ex.InnerException != null) 
     { 
      LogHelper.LogError("Exception InnerException :" + ex.InnerException); 
     } 
     LogHelper.LogError("Exception StackTrace :" + ex.StackTrace); 
     LogHelper.LogError("OutLookMailStart -> GetAttachmentsFromEmail Exception"); ; 
    } 
    LogHelper.LogMessage("<----- GetAttachmentsFromEmail End ----->"); 


} 
+1

這將遠遠優於解釋而不是龐大的代碼轉儲。 – Rob

相關問題