2013-02-26 2 views
0

Я создаю программу, которая отправляет текстовое сообщение, а затем в зависимости от ответа я хочу выполнить определенное действие. В любом случае вот мой код:outlook загрузить email body

using Microsoft.Office.Interop.Outlook; 
using Outlook = Microsoft.Office.Interop.Outlook; 

static void Main() 
{       
    var outlook = new Microsoft.Office.Interop.Outlook.Application(); 

    // fire event when a new email arives 
    outlook.NewMailEx += new ApplicationEvents_11_NewMailExEventHandler(oApp_NewMailEx); 

    // etc 
} 

static void oApp_NewMailEx(string EntryIDCollection) 
{ 
    var outlook = new Microsoft.Office.Interop.Outlook.Application(); 
    MailItem temp = (MailItem)outlook.Session.GetItemFromID(EntryIDCollection, Missing.Value); 

    var body = temp.Body; // the body of the email is null! I tried waiting and it is null until I open it... 
    Console.WriteLine(body); 
} 

Эта часть не важна, но я посылаю «текстовое сообщение» с помощью этой функции:

// send text message "att.txt.net only works with at&t phones" 
public static int SendEmail(string recipeint = "[email protected]") 
{ 
     try 
     { 
      // Create the Outlook application by using inline initialization. 
      Outlook.Application oApp = new Outlook.Application(); 


      //Create the new message by using the simplest approach. 
      Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); 



      Outlook.Accounts accounts = oMsg.Session.Accounts; 
      foreach (Outlook.Account account in accounts) 
      { 
       // When the e-mail address matches, send the mail. 
       if (account.SmtpAddress.Contains("gmail")) 
       { 
         oMsg.SendUsingAccount = account;        
         break; 
       } 
      } 

      // If you want to, display the message. 
      oMsg.Display(true); //modal 


      //Add a recipient.     
      Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add(recipeint); 
      oRecip.Resolve(); 

      //Set the basic properties. 
      oMsg.Subject = "This is the subject of the test message"; 
      oMsg.Body = "This is the text in the message."; 


      //Add an attachment. 
      // TODO: change file path where appropriate 
      //String sSource = "C:\\setupxlg.txt"; 
      //String sDisplayName = "MyFirstAttachment"; 
      //int iPosition = (int)oMsg.Body.Length + 1; 
      //int iAttachType = (int)Outlook.OlAttachmentType.olByValue; 
      //Outlook.Attachment oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName); 



      //Send the message. 
      oMsg.Save(); 
      oMsg.Send(); 

      //Explicitly release objects. 
      oRecip = null; 
      //oAttach = null; 
      oMsg = null; 
      oApp = null; 
     } 

      // Simple error handler. 
     catch (System.Exception e) 
     { 
      Console.WriteLine("{0} Exception caught: ", e); 
     } 

     //Default return value. 
     return 0; 
} 

Так что я могу отправить по электронной почте с моим аккаунтом Gmail и когда я отвечаю на текстовое сообщение, функция oApp_NewMailEx выполняется с идентификатором нового сообщения электронной почты. Я могу получить предмет, но тело не загружается, пока я не надвигаю указатель мыши на электронную почту или не открываю письмо. Я уже остыл 2 минуты на другом потоке, а затем попытался увидеть тело, и он все еще был нулевым.


Редактировать примечание, чтобы сделать эту работу у меня есть:

enter image description here

Это выглядит серым, потому что я не бежал перспективы в качестве администратора. Если вы запускаете Outlook в качестве администратора, вы сможете обновить параметры безопасности.

Я также импортировал библиотеку объектов Microsoft Outlook 14.0 в качестве ссылки.

ответ

0

Как только я получил электронное письмо, я вызвал метод отправки и получения. Подождите немного, а затем я смог прочитать тело.

outlook.Session.SendAndReceive(false); 
Смежные вопросы