Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the body of an incoming email in an Outlook Addin

Tags:

c#

email

outlook

I want to process incoming mails coming from an exchange server and save it in my mail box. As of now I can get an alert for every incoming mail.

How can I get the body of the email to process it?

   public partial class ThisAddIn
   {
            private void ThisAddIn_Startup(object sender, System.EventArgs e)
            {
                this.Application.NewMail += new ApplicationEvents_11_NewMailEventHandler(AlertWhenNewMail);
            }
            void AlertWhenNewMail()
            {
                MessageBox.Show("New Email Recieved");
            }

            private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
            {
            }
            #region VSTO generated code
            private void InternalStartup()
            {
               this.Startup += new System.EventHandler(ThisAddIn_Startup);
               this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
            }
            #endregion
    }

Also, how to save the email and then just store it in the inbox folder?

like image 457
c_prog_90 Avatar asked Jan 20 '23 08:01

c_prog_90


2 Answers

To get to the actual mailItem, use the entryID passed in the newMailEx event. Your response to other posts suggests this doesn't work for you somehow, but I'll assume we'll get that sorted out and provide you some example code:

void MyApplication_NewMailEx(string anEntryID)
{
  Outlook.NameSpace namespace = this.GetNamespace("MAPI");  
  Outlook.MAPIFolder folder = this.Session.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderInbox );
  Outlook.MailItem mailItem = (Outlook.MailItem) outlookNS.GetItemFromID( anEntryID, folder.StoreID );

  // ... process the mail item
}

To answer the second part of your question, once you get hold of the mail item through this event it has already been saved into your inbox, so no need to do anything there. You'd save it to disk using MailItem.SaveAs.

like image 172
Paul-Jan Avatar answered Jan 29 '23 09:01

Paul-Jan


Instead of Application.NewMail event, try Application.NewMailEx with gives you a parameter EntryIDCollection (A string representing an Entry ID of an item received in the Inbox) with which you should be able to retrieve the new email. MSDN page has a simple example.

like image 28
Bala R Avatar answered Jan 29 '23 08:01

Bala R