/// <summary> /// Removes a specific event or a series of events /// </summary> /// <param name="objItems">Contains all the event items in a specific calendar/folder</param> /// <param name="subject">Subject of the event to delete</param> /// <param name="eventDate">If specified, this specific event is deleted instead of all events with subject</param> internal static void RemoveEvent(Outlook.Items objItems, string subject, string eventDate) { string methodTag = "RemoveEvent"; LogWriter.WriteInfo(TAG, methodTag, "Starting: " + methodTag + " in " + TAG); Outlook.AppointmentItem agendaMeeting = null; if (eventDate == null) { objItems.Sort("[Subject]"); objItems.IncludeRecurrences = true; LogWriter.WriteInfo(TAG, methodTag, "Attempting to find event with subject: " + subject); agendaMeeting = objItems.Find("[Subject]=" + subject); if (agendaMeeting == null) { LogWriter.WriteWarning(TAG, methodTag, "No event found with subject: " + subject); } else { LogWriter.WriteInfo(TAG, methodTag, "Removing all events with subject: " + subject); do { agendaMeeting.Delete(); agendaMeeting = objItems.FindNext(); LogWriter.WriteInfo(TAG, methodTag, "Event found and deleted, finding next"); } while (agendaMeeting != null); LogWriter.WriteInfo(TAG, methodTag, "All events with subject: " + subject + " found and deleted"); } } else { LogWriter.WriteInfo(TAG, methodTag, "Finding event with subject" + subject + " and date: " + eventDate); agendaMeeting = objItems.Find("[Subject]=" + subject); if (agendaMeeting == null) { LogWriter.WriteWarning(TAG, methodTag, "No event found with subject: " + subject); } else { Outlook.RecurrencePattern recurrPatt = agendaMeeting.GetRecurrencePattern(); agendaMeeting = recurrPatt.GetOccurrence(DateTime.Parse(eventDate)); agendaMeeting.Delete(); LogWriter.WriteInfo(TAG, methodTag, "Event found and deleted"); } } }
private void SearchInBox() { Outlook.MAPIFolder inbox = this.Application.ActiveExplorer().Session. GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); MessageBox.Show(inbox.Folders.Count.ToString()); foreach (Outlook.Folder item in inbox.Folders) { MessageBox.Show(item.Name); } Outlook.Items items = inbox.Items; Outlook.MailItem mailItem = null; object folderItem; string subjectName = string.Empty; string filter = "[Subject] > 's' And [Subject] <'u'"; folderItem = items.Find(filter); while (folderItem != null) { mailItem = folderItem as Outlook.MailItem; if (mailItem != null) { subjectName += "\n" + mailItem.Subject; } folderItem = items.FindNext(); } subjectName = " The following e-mail messages were found: " + subjectName; MessageBox.Show(subjectName); }
private OutLook.ContactItem FindContactEmailByID(String ID) { OutLook.NameSpace outlookNameSpace = OutLookApp.GetNamespace("MAPI"); if (folder == null) { folder = OutLookApp.Session.GetDefaultFolder( OutLook.OlDefaultFolders.olFolderContacts).Folders[ tbContactsFolder.Text] as OutLook.Folder; } OutLook.Items contactItems = folder.Items; try { OutLook.ContactItem contact = (OutLook.ContactItem)contactItems. Find(String.Format("[Organizational ID]='{0}'", ID)); if (contact != null) { return(contact); } else { } } catch (Exception ex) { } return(null); }
public Outlook.ContactItem OutlookContactsFind(string filterStr) { Outlook.MAPIFolder mAPIFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts); Outlook.Items items = mAPIFolder.Items; Outlook.ContactItem ResultItem = null; items.Sort("[Title]"); try { ResultItem = items.Find(filterStr); } catch (Exception) { return(null); } finally { if (mAPIFolder != null) { Marshal.ReleaseComObject(mAPIFolder); } if (items != null) { Marshal.ReleaseComObject(items); } } return(ResultItem); }
private void ProcessMissedItems() { // We process all items in the folder that we've missed (e.g. Outlook was closed, or too many changes happened at once) // We do this by looking for any items that do not have our custom property set Outlook.Items missedItems = _watchedFolder.Items; // As we're filtering on a custom property that we haven't added to the folder, we need to add the // property type (0x0000001f) to the end of the property definition (otherwise, our filter won't work) string filter = String.Format("@SQL=NOT \"{0}/0x0000001f\" LIKE 'P-%'", _propItemProcessedDate); //AddLog("Filter: " + filter); object missedItem = missedItems.Find(filter); if (missedItem == null) { return; } ProcessItem(missedItem); while (missedItem != null) { missedItem = null; missedItem = missedItems.FindNext(); if (missedItem != null) { ProcessItem(missedItem); } } }
private Outlook.ContactItem SearchOutlookContacts(string name, Outlook.NameSpace _ns = null) { Outlook.NameSpace ns = _ns; if (ns == null) { ns = Globals.ThisAddIn.Application.GetNamespace("MAPI"); } if (ns != null) { Outlook.MAPIFolder folder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts); Outlook.Items contacts = folder.Items; try { var contact = (Outlook.ContactItem)contacts.Find(string.Format("[FullName]='{0}'", name)); return(contact); } catch (Exception) { return(null); } } return(null); }
public string findLicenseMails() { StringBuilder sb = new StringBuilder(); Microsoft.Office.Interop.Outlook._MailItem InboxMailItem = null; Microsoft.Office.Interop.Outlook.Items oItems = MyInbox.Items; string Query = "[Subject] contains 'Your license order'"; //string filter = "urn:schemas:mailheader:subject LIKE '%" + wordInSubject + "%'"; InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.Find(Query); while (InboxMailItem != null) { //ListViewItem myItem = lvwMails.Items.Add(InboxMailItem.SenderName); //myItem.SubItems.Add(InboxMailItem.Subject); sb.Append(InboxMailItem.SenderName + ": "); sb.Append(InboxMailItem.Subject + "\r\n"); string AttachmentNames = string.Empty; foreach (Microsoft.Office.Interop.Outlook.Attachment item in InboxMailItem.Attachments) { AttachmentNames += item.DisplayName; sb.Append("\t" + item.DisplayName + "\r\n"); //item.SaveAsFile(this.GetAttachmentPath(item.FileName, "c:\\test\\attachments\\")); } //myItem.SubItems.Add(AttachmentNames); //InboxMailItem.Delete(); InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.FindNext(); } return(sb.ToString()); }
private bool IsContactExist(string FullName) { bool found = false; Outlook.NameSpace outlookNameSpace = this.Application.GetNamespace("MAPI"); Outlook.MAPIFolder contactsFolder = outlookNameSpace.GetDefaultFolder( Microsoft.Office.Interop.Outlook. OlDefaultFolders.olFolderContacts); Outlook.Items contactItems = contactsFolder.Items; try { Outlook.ContactItem contact = (Outlook.ContactItem)contactItems. Find(String.Format("[FullName]='{0}'", FullName)); if (contact != null) { found = true; } else { found = false; } } catch (Exception ex) { throw ex; } return(found); }
private void FindContactEmailByName(string firstName, string lastName) { Outlook.NameSpace outlookNameSpace = this.Application.GetNamespace("MAPI"); Outlook.MAPIFolder contactsFolder = outlookNameSpace.GetDefaultFolder( Microsoft.Office.Interop.Outlook. OlDefaultFolders.olFolderContacts); Outlook.Items contactItems = contactsFolder.Items; try { Outlook.ContactItem contact = (Outlook.ContactItem)contactItems. Find(String.Format("[FirstName]='{0}' and " + "[LastName]='{1}'", firstName, lastName)); if (contact != null) { contact.Display(true); } else { MessageBox.Show("The contact information was not found."); } } catch (Exception ex) { throw ex; } }
public override IContactItem SearchContact(string phoneNumber, string fullName) { try { ToggleSecurityWarning(true); Microsoft.Office.Interop.Outlook.Items contactItems = GetBaseContacts(); string formattedPhone = WOSI.Utilities.StringUtils.FormatPhoneNumber(phoneNumber); //string qry = "[BusinessTelephoneNumber] = '{0}' or [FullName] = '{1}' or [BusinessTelephoneNumber] = '{2}'"; string firstPassQry = String.Format(Query, phoneNumber, fullName); Microsoft.Office.Interop.Outlook.ContactItem contactItem = contactItems.Find(firstPassQry) as Microsoft.Office.Interop.Outlook.ContactItem; if (contactItem == null) { string secondPassQry = String.Format(Query, formattedPhone, fullName); contactItem = contactItems.Find(secondPassQry) as Microsoft.Office.Interop.Outlook.ContactItem; } IContactItem outlookItem = null; if (contactItem != null) { outlookItem = ContactItemFactory.CreateContactItem(this, contactItem); } return(outlookItem); } catch (System.Exception ex) { FireContactManagerFailureEvent(ex); return(null); } finally { ToggleSecurityWarning(false); } }
private static List <EmailParsingData> GetDeliveryReportList(string filter) { try { var mailBoxContent = new List <EmailParsingData>(); Outlook.Items folderItems = null; Outlook.MAPIFolder inboxFolder = null; foreach (dynamic folder in ThisAddIn.thisApplication.GetNamespace("MAPI").Folders) { var subFolders = GpiOutlookWrapper.GetFolder(folder.FolderPath); foreach (Outlook.MAPIFolder subFolder in subFolders.Folders) { if (subFolder.FullFolderPath.Contains("Уведомления о прочтении") && (subFolder.FullFolderPath.Contains("Канцелярия") || subFolder.FullFolderPath.Contains("kancelaria"))) { inboxFolder = subFolder; } } Marshal.ReleaseComObject(subFolders); } if (inboxFolder == null) { return(mailBoxContent); } folderItems = inboxFolder.Items; folderItems.Sort("[CreationTime]", true); var item = folderItems.Find(filter); while (item != null) { var parsingData = new EmailParsingData(); parsingData.Subject = item.Subject; parsingData.ItemClass = item.MessageClass; parsingData.CreationTime = item.CreationTime; mailBoxContent.Add(parsingData); Marshal.ReleaseComObject(item); item = folderItems.FindNext(); } return(mailBoxContent); } catch (Exception ex) { throw; } }
//gavdcodeend 07 //gavdcodebegin 08 private void btnDeleteContact_Click(object sender, RibbonControlEventArgs e) { Outlook.Application myApplication = Globals.ThisAddIn.Application; Outlook.NameSpace outlookNameSpace = myApplication.GetNamespace("MAPI"); Outlook.MAPIFolder myContactsFolder = outlookNameSpace.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderContacts); Outlook.Items myContactItems = myContactsFolder.Items; Outlook.ContactItem myContact = (Outlook.ContactItem)myContactItems. Find("[FirstName]='a' and [LastName]='b'"); if (myContact != null) { myContact.Delete(); } }
private Outlook.ContactItem FindContactByName(string firstName, string lastName) { Outlook.NameSpace outlookNameSpace = this._application.GetNamespace("MAPI"); Outlook.MAPIFolder contactsFolder = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts); Outlook.Items contactItems = contactsFolder.Items; try { Outlook.ContactItem contact = contactItems.Find(String.Format("[FirstName]='{0}' and [LastName]='{1}'", firstName, lastName)) as Outlook.ContactItem; return(contact); } catch { return(null); } }
/// <summary> /// Updates a specific instance of an event from another calendar in Outlook /// The other shared calendar must be opened in outlook before running. /// Utilizes the updateEvent function in the common library. /// </summary> /// <param name="subject">Title of the Event to update</param> /// <param name="eventDate">The date of the specific event M/d/yyyy hh:mm:ss tt</param> /// <param name="updatedTitle">Updated title. not required</param> /// <param name="updatedStartDate">Updated start date. not required</param> /// <param name="updatedDuration">updated duration. not required</param> /// <param name="otherCalendar">Name of the calendar the event is located in</param> /// <param name="recipients">Recipients to add to the updated event</param> public void UpdateOtherCalendarEvent(string subject, string eventDate, string updatedTitle, string updatedStartDate, string updatedDuration, string otherCalendar, string[] recipients) { string methodTag = "UpdateOtherCalendarEvent"; LogWriter.WriteInfo(TAG, methodTag, "Starting: " + methodTag + " in " + TAG); Outlook.Application app = null; Outlook.AppointmentItem agendaMeeting = null; Outlook.NameSpace NS = null; Outlook.MAPIFolder objFolder = null; Outlook.MailItem objTemp = null; Outlook.Recipient objRecip = null; Outlook.Items objItems = null; app = new Outlook.Application(); NS = app.GetNamespace("MAPI"); objTemp = app.CreateItem(Outlook.OlItemType.olMailItem); objRecip = objTemp.Recipients.Add(otherCalendar); objTemp = null; LogWriter.WriteInfo(TAG, methodTag, "Attempting to resolve recipient object for: " + otherCalendar); objRecip.Resolve(); if (objRecip.Resolved) { objFolder = NS.GetSharedDefaultFolder(objRecip, Outlook.OlDefaultFolders.olFolderCalendar); objItems = objFolder.Items; agendaMeeting = objItems.Find("[Subject]=" + subject); agendaMeeting = CommonLibrary.UpdateEvent(agendaMeeting, eventDate, updatedTitle, updatedStartDate, updatedDuration, recipients); LogWriter.WriteInfo(TAG, methodTag, "Sending event"); agendaMeeting.Send(); LogWriter.WriteInfo(TAG, methodTag, subject + " sucessfully sent"); } else { LogWriter.WriteWarning(TAG, methodTag, "Recipient object was not sucessfully resolved"); throw new NullReferenceException(); } return; }
public static ContactItem GetContactItem(string name) { var strs = name.Split('('); name = strs[0].Trim(); Outlook.MAPIFolder contactFolder = OutlookSync.Syncer.CurrentApplication.Session.GetDefaultFolder(Outlook.OlDefaultFolders .olFolderContacts); Outlook.Items contactItems = contactFolder.Items; Outlook.ContactItem contact = (Outlook.ContactItem)contactItems.Find($"[FirstName]='{name}' OR [Email1Address]='{name}'"); if (contact == null) { return(null); } ContactItem item = new ContactItem(contact.FirstName, contact.Email1Address, contact.PrimaryTelephoneNumber); return(item); }
/// <summary> /// Updates a specific event (a single event or one instance of a recurrence) /// that is currently in the main calendar of the open Outlook Application /// Utilizes the common methods found in the common library class /// </summary> /// <param name="subject">The subject of the event to edit</param> /// <param name="eventDate">The date of the specific event M/d/yyyy hh:mm:ss tt</param> /// <param name="updatedTitle">An updated title if desired</param> /// <param name="updatedStartDate">An updated start date if desired</param> /// <param name="updatedDuration">An updated duration if desired</param> /// <param name="recipients">New recipients to add</param> public void UpdateMainCalendarEvent(string subject, string eventDate, string updatedTitle, string updatedStartDate, string updatedDuration, string[] recipients) { string methodTag = "UpdateMainCalendarEvent"; LogWriter.WriteInfo(TAG, methodTag, "Starting: " + methodTag + " in " + TAG); Outlook.Application app = null; Outlook.AppointmentItem agendaMeeting = null; Outlook.Items objItems = null; Outlook.MAPIFolder objFolder = null; app = new Outlook.Application(); Outlook.NameSpace NS = app.GetNamespace("MAPI"); agendaMeeting = (Outlook.AppointmentItem)app.CreateItem(Outlook.OlItemType.olAppointmentItem); objFolder = NS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); objItems = objFolder.Items; LogWriter.WriteInfo(TAG, methodTag, "Attempting to find event with subject: " + subject); agendaMeeting = objItems.Find("[Subject]=" + subject); if (agendaMeeting == null) { LogWriter.WriteWarning(TAG, methodTag, "Failed to find event with subject: " + subject); throw new NullReferenceException(); } LogWriter.WriteInfo(TAG, methodTag, "Found event with subject: " + subject + " and updating details"); agendaMeeting = CommonLibrary.UpdateEvent(agendaMeeting, eventDate, updatedTitle, updatedStartDate, updatedDuration, recipients); LogWriter.WriteInfo(TAG, methodTag, "Sending event"); agendaMeeting.Send(); LogWriter.WriteInfo(TAG, methodTag, subject + " sucessfully sent"); return; }
public void GetEmails() { //MessageBox.Show("In GetEmails"); Outlook.MAPIFolder inbox = null; Outlook.NameSpace ns = null; Outlook.Items items = null; Outlook.MailItem mailItem = null; string subjectName = string.Empty; DateTime lastrunDate = Convert.ToDateTime(File.ReadLines("log.txt").Last()); string subjectFilter = "[Subject] = 'Cutler / (1) DEFICIT EXECUTIONS'"; string subjectFilter2 = "[Subject] = 'STOCK LOAN EXECUTION'"; string subjectFilter3 = "[Subject] = 'CUTLER/ (1) DEFICIT EXECUTIONS'"; List <string> subjectFilters = new List <string>(); subjectFilters.Add(subjectFilter); subjectFilters.Add(subjectFilter2); subjectFilters.Add(subjectFilter3); try { if (Process.GetProcessesByName("OUTLOOK").Count() > 0) { //Check if Outlook is open. //MessageBox.Show("Outlook Is Open"); Outlook.Application applic = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application; inbox = applic.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); } else { //Open Outlook if closed. //MessageBox.Show("Outlook is Closed...Opening an instance of Outlook"); Outlook.Application app = new Outlook.Application(); ns = app.GetNamespace("MAPI"); inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); ns = null; } foreach (string subject in subjectFilters) { object folderItem; items = inbox.Items; folderItem = items.Find(subject); //MessageBox.Show("Checking for Emails since " + lastrunDate + " with subject " + subject); while (folderItem != null) { mailItem = folderItem as Outlook.MailItem; //Check if email rcvd after last run date. if (mailItem != null && Convert.ToDateTime(mailItem.ReceivedTime) > lastrunDate) { emails.Add(mailItem); subjectName += "\n" + mailItem.Subject + mailItem.SenderEmailAddress + mailItem.SentOn; } folderItem = items.FindNext(); } } } catch (Exception e) { MessageBox.Show("{0} Exception caught.", e.Message); } finally { if (items != null) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(items); } if (inbox != null) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(inbox); } } if (emails.Count == 0) { MessageBox.Show("No Emails Found"); Environment.Exit(0); } else { MessageBox.Show("Found " + emails.Count + " Emails"); } return; }
public string GetOneMail(string EmailAddress, string Profile, string LogPath, string LogData, string FolderName, string EmailType, string AttachmentSavePath = "", string RetainOriginalAttName = "true", string EmailSavePath = "", string EmailExtension = "", string MarkAsRead = "", string MoveEmailToFolder = "") { string results = ""; try { Outlook.Items folderItems = null; Outlook.MailItem foundMail = null; object foundItem = null; Connection conn = null; NameSpace nameSpace = null; string log = ""; Outlook.Folder outboxFolder = null; Outlook.MAPIFolder oFolder; log = "Creating new connection to Outlook"; conn = new Connection(); Outlook.Application application = conn.InitializeConnection(EmailAddress, Profile, out nameSpace, out outboxFolder, out oFolder); MAPIFolder subFolder = null; if (FolderName.ToLower() == "inbox") { subFolder = oFolder; } else { foreach (MAPIFolder folder in oFolder.Folders) { if (folder.Name == FolderName) { subFolder = folder; break; } } } //Console.WriteLine(subFolder.UnReadItemCount.ToString() ); log = "Connected to folder " + subFolder.Name; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); if (subFolder.DefaultItemType == Outlook.OlItemType.olMailItem) { folderItems = subFolder.Items; //Creating filter for unread/read or all if (EmailType.ToLower() == "unread") { foundItem = folderItems.Find("[Unread]=true"); //Console.WriteLine(subFolder.UnReadItemCount.ToString() ); log = "Obtaining only UNREAD emails. Total found: " + subFolder.UnReadItemCount.ToString(); } else if (EmailType.ToLower() == "read") { foundItem = folderItems.Find("[Unread]=false"); log = "Obtaining only READ emails"; } else if (EmailType.ToLower() == "all") { foundItem = (Outlook.MailItem)subFolder.Items.GetFirst(); log = "Obtaining ALL emails"; } else { return("Incorrect filter. Allowed only: read/unread/all"); } string SenderEmailAddress = ""; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); while (foundItem != null) { try { if (foundItem is Outlook.MailItem) { foundMail = foundItem as Outlook.MailItem; if (foundMail.Sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || foundMail.Sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { Outlook.ExchangeUser exchUser = foundMail.Sender.GetExchangeUser(); if (exchUser != null) { SenderEmailAddress = exchUser.PrimarySmtpAddress; } } else { SenderEmailAddress = foundMail.SenderEmailAddress.ToString(); } log = "Found email - Subject: " + foundMail.Subject + " From: " + foundMail.SenderEmailAddress.ToString() + " Received date: " + foundMail.ReceivedTime.ToString(); File.AppendAllText(LogPath, LogData + log + Environment.NewLine); if (AttachmentSavePath != "") { int fileID = 0; log = "Attachment saving requested"; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); foreach (Attachment attachment in foundMail.Attachments) { int strCID = (int)attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003"); if (strCID != 0) { continue; } if (RetainOriginalAttName.ToLower() == "false") { fileID++; string extension = Path.GetExtension(attachment.FileName); log = "Saving: " + AttachmentSavePath + attachment.FileName; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); attachment.SaveAsFile(AttachmentSavePath + fileID + extension); } else { log = "Saving: " + AttachmentSavePath + attachment.FileName; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); attachment.SaveAsFile(AttachmentSavePath + attachment.FileName); } } } if (EmailSavePath != "") { log = "Email saving requested"; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); Regex rgx = new Regex("[^a-zA-Z0-9 ]"); string emailfilename = rgx.Replace(foundMail.Subject.ToString(), ""); log = "Email name changed to: " + emailfilename; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); if (EmailExtension != "") { if (EmailExtension.ToLower() == "mht") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olMHTML); } else if (EmailExtension.ToLower() == "msg") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olMSG); } else if (EmailExtension.ToLower() == "html") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olHTML); } else if (EmailExtension.ToLower() == "txt") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olTXT); } else if (EmailExtension.ToLower() == "rtd") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olRTF); } //foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension); log = "Saving email: " + EmailSavePath + emailfilename + "." + EmailExtension; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); } else { log = "Saving email: " + EmailSavePath + emailfilename + ".msg"; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); foundMail.SaveAs(EmailSavePath + emailfilename + ".msg"); } } if (MarkAsRead.ToLower() == "true") { foundMail.UnRead = false; foundMail.Save(); } if (MoveEmailToFolder != "") { foreach (MAPIFolder folder in oFolder.Folders) { if (folder.Name == MoveEmailToFolder) { foundMail.Move(folder); } } } } else { if (foundItem != null) { Marshal.ReleaseComObject(foundItem); } foundItem = folderItems.FindNext(); continue; } try { //results = SenderEmailAddress.ToString() + "|#|" + foundMail.Subject.ToString() + "|#|" + foundMail.ReceivedTime.ToString(); results = foundMail.SenderEmailAddress.ToString() + "|#|" + foundMail.Subject + "|#|" + foundMail.ReceivedTime.ToString(); } catch (System.Exception) { } if (foundItem != null) { Marshal.ReleaseComObject(foundItem); } } catch (System.Exception) { } // //Console.WriteLine(foundItem.ToString()); break; } } else { foundItem = folderItems.FindNext(); } if (results == "") { return("No emails for processing"); } return(results); } catch (System.Exception ex) { return("Failed: " + ex.ToString()); } }
/// <summary> /// Event handler for CGrabber application new mail arrived event. /// </summary> /// <param name="entryIdCollection">Entry Id collection.</param> private void CGrabberApplicationNewMailEx(string entryIdCollection) { var namespaceitem = this.cgrabberApplication.GetNamespace("MAPI"); var stores = this.cgrabberApplication.Session.Stores; foreach (var folder in from Outlook.Store store in stores select store.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)) { try { var mailItem = (Outlook.MailItem)namespaceitem.GetItemFromID(entryIdCollection, folder.StoreID); if (null == mailItem) { return; } var searchResult = false; if (mailItem.Body != null) { searchResult = SearchKeywords.Any(keyword => mailItem.Body.IndexOf(keyword) != -1); } var searchResultHtmlBody = false; if (mailItem.HTMLBody != null) { searchResultHtmlBody = SearchKeywords.Any(keyword => mailItem.HTMLBody.IndexOf(keyword) != -1); } var subjectSearchResult = false; if (mailItem.Subject != null) { subjectSearchResult = SearchKeywords.Any(keyword => mailItem.Subject.IndexOf(keyword) != -1); } if (!searchResult && !searchResultHtmlBody && !subjectSearchResult) { return; } Outlook.MAPIFolder contactsFolder = null; Outlook.Items items = null; Outlook.ContactItem contact = null; try { contactsFolder = this.cgrabberApplication.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts); items = contactsFolder.Items; var filter = "[Email1Address] = '" + mailItem.SenderEmailAddress + "'"; Outlook.ContactItem existingContact = null; existingContact = items.Find(filter) as Outlook.ContactItem; if (existingContact != null) { return; } else { filter = "[Email2Address] = '" + mailItem.SenderEmailAddress + "'"; existingContact = items.Find(filter) as Outlook.ContactItem; if (existingContact != null) { return; } else { filter = "[Email3Address] = '" + mailItem.SenderEmailAddress + "'"; existingContact = items.Find(filter) as Outlook.ContactItem; if (existingContact != null) { return; } else { contact = items.Add(Outlook.OlItemType.olContactItem) as Outlook.ContactItem; if (null == contact) { return; } contact.Email1Address = mailItem.SenderEmailAddress; contact.Email1DisplayName = mailItem.SenderName; contact.Save(); } } } } catch (Exception) { } finally { if (contact != null) { Marshal.ReleaseComObject(contact); } if (items != null) { Marshal.ReleaseComObject(items); } if (contactsFolder != null) { Marshal.ReleaseComObject(contactsFolder); } } } catch (Exception) { continue; } } }
/// <summary> /// The get mail box content. /// </summary> /// <param name="inboxFolder"> /// The inbox folder. /// </param> /// <param name="filterParameters"> /// The filter Parameters. /// </param> /// <param name="messageClass"> /// The message Class. /// </param> /// <returns> /// The list of EmailParsingData. /// </returns> public static List <EmailParsingData> GetMailBoxContent(Outlook.MAPIFolder inboxFolder, FilterParametersData filterParameters, string messageClass = "IPM.Note") { var mailBoxContent = new List <EmailParsingData>(); if (inboxFolder == null) { return(mailBoxContent); } Outlook.Items folderItems = null; var start = DateTime.MinValue; try { folderItems = inboxFolder.Items; folderItems.Sort("[CreationTime]", true); start = DateTime.Now; var deliveryReportFilter = GenerateFilter(filterParameters, "REPORT.IPM.Note.DR"); var deliveryReportList = GetDeliveryReportList(deliveryReportFilter); var filter = GenerateFilter(filterParameters, messageClass); var item = folderItems.Find(filter); while (item != null) { if (!CheckSubjectFilter(filterParameters, item.Subject)) { Marshal.ReleaseComObject(item); item = folderItems.FindNext(); continue; } var parsingData = GetEmailParsingData(item); if (parsingData.Subject.Contains(@"15292")) { var x = 0; } parsingData.Status = GetEmailStatusFromConversation(item, parsingData.CreationTime); if (parsingData.Status == EmailStatus.Unknown) { parsingData.Status = GetEmailStatusFromSubject(item.Subject, deliveryReportList); } if (!CheckStatusFilter(filterParameters, parsingData.Status)) { Marshal.ReleaseComObject(item); item = folderItems.FindNext(); continue; } mailBoxContent.Add(parsingData); Marshal.ReleaseComObject(item); item = folderItems.FindNext(); } } catch (Exception ex) { ErrorList.Add(MethodBase.GetCurrentMethod().Name + " " + ex.Message); } finally { if (folderItems != null) { Marshal.ReleaseComObject(folderItems); } } var dyration = (DateTime.Now - start).TotalSeconds; return(mailBoxContent.OrderByDescending(c => c.CreationTime).ToList()); }
/// <summary> /// Adds new appointment for the specified date range /// </summary> /// <param name="PobjItem"></param> private void getAppointments(ExtendedRecipient PobjRecipient, DateTime PobjDay, bool PbolMeetingsOnly, bool PbolExcludePrivate) { try { // Start filling in the rest... Outlook.MAPIFolder LobjFolder = null; try { LobjFolder = Common.IsRecipientValid(PobjRecipient.InteropRecipient); if (LobjFolder == null) { throw new Exception(); } } catch (Exception PobjEx) { throw new Exception("Recipient calendar folder cannot be found. " + "This might be because you have not added them as a shared calendar. " + PobjEx.Message); } Outlook.Items LobjItems = LobjFolder.Items; if (LobjItems == null) { throw new Exception("Unable to access recipient items. You may not have permission."); } try { LobjItems.Sort("[Start]"); // sort the items } catch (Exception PobjEx) { throw new Exception("Recipient calendar folder cannot be accessed or sorted. " + "This might be because you might not have permission. " + PobjEx.Message); } LobjItems.IncludeRecurrences = true; // be sure to include recurrences string LstrDay = PobjDay.ToShortDateString(); // set the find string to today 0:00 to 23:59:59 string LstrFind = "[Start] <= \"" + LstrDay + " 11:59 PM\"" + " AND [End] > \"" + LstrDay + " 12:00 AM\""; // find the first appointment for the day Outlook.AppointmentItem LobjAppt = LobjItems.Find(LstrFind); while (LobjAppt != null) { if (LobjAppt.MeetingStatus == Outlook.OlMeetingStatus.olNonMeeting && PbolMeetingsOnly) { // skip - this is an appointment only // and we are limiting to only meetings } else if (PbolExcludePrivate == true && LobjAppt.Sensitivity == Microsoft.Office.Interop.Outlook.OlSensitivity.olPrivate) { // skip - this is an private item // and we are not includeing private items } else { ExtendedAppointment LobjNew = new ExtendedAppointment(LobjAppt, PobjRecipient); if (!Appointments.Contains(LobjNew)) { // now add the appointment Appointments.Add(LobjNew); } else { Appointments.FindItem(LobjNew).AddRecipient(PobjRecipient); } } // get the next item LobjAppt = LobjItems.FindNext(); } } catch (Exception PobjEx) { throw new Exception("Failed while processing " + PobjDay.ToLongDateString() + " for " + PobjRecipient.RecipientName + ". " + PobjEx.Message); } }
//####################################### TESTING ########################################### /* * public void getLicenseMails() //see http://blogs.msdn.com/b/philliphoff/archive/2008/03/03/filter-outlook-items-by-date-with-linq-to-dasl.aspx * { * Microsoft.Office.Interop.Outlook.Folder folder = (Microsoft.Office.Interop.Outlook.Folder)MailNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); * * string subject = sLicenseSubject;// "Your license order"; * * var results = * * from item in folder.Items.AsQueryable<Microsoft.Office.Interop.Outlook.Extensions.Linq.Mail>() * * where item.Subject.Contains(subject) && item.Attachments.Count>0 //item.CreationTime <= DateTime.Now - new TimeSpan(7, 0, 0, 0) * * select item; * * foreach (var result in results) * { * System.Diagnostics.Debug.WriteLine(String.Format("Body: {0}", result)); * } * } */ private void SearchRecurringAppointments() { Microsoft.Office.Interop.Outlook.AppointmentItem appt = null; Microsoft.Office.Interop.Outlook.Folder folder = MailNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox) //Microsoft.Office.Interop.Outlook.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar) as Microsoft.Office.Interop.Outlook.Folder; // Set start value DateTime start = new DateTime(2006, 8, 9, 0, 0, 0); // Set end value DateTime end = new DateTime(2006, 12, 14, 0, 0, 0); // Initial restriction is Jet query for date range string filter1 = "[Start] >= '" + start.ToString("g") + "' AND [End] <= '" + end.ToString("g") + "'"; Microsoft.Office.Interop.Outlook.Items calendarItems = folder.Items.Restrict(filter1); calendarItems.IncludeRecurrences = true; calendarItems.Sort("[Start]", Type.Missing); // Must use 'like' comparison for Find/FindNext string filter2; filter2 = "@SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " like '%Office%'"; // Create DASL query for additional Restrict method string filter3; if (MailNS.DefaultStore.IsInstantSearchEnabled)// Microsoft.Office.Interop.Outlook.Application.Session.DefaultStore.IsInstantSearchEnabled) { filter3 = "@SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " ci_startswith 'Office'"; } else { filter3 = "@SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " like '%Office%'"; } // Use Find and FindNext methods appt = calendarItems.Find(filter2) as Microsoft.Office.Interop.Outlook.AppointmentItem; while (appt != null) { StringBuilder sb = new StringBuilder(); sb.AppendLine(appt.Subject); sb.AppendLine("Start: " + appt.Start); sb.AppendLine("End: " + appt.End); System.Diagnostics.Debug.WriteLine(sb.ToString()); // Find the next appointment appt = calendarItems.FindNext() as Microsoft.Office.Interop.Outlook.AppointmentItem; } // Restrict calendarItems with DASL query Microsoft.Office.Interop.Outlook.Items restrictedItems = calendarItems.Restrict(filter3); foreach (Microsoft.Office.Interop.Outlook.AppointmentItem apptItem in restrictedItems) { StringBuilder sb = new StringBuilder(); sb.AppendLine(apptItem.Subject); sb.AppendLine("Start: " + apptItem.Start); sb.AppendLine("End: " + apptItem.End); sb.AppendLine(); System.Diagnostics.Debug.WriteLine(sb.ToString()); } }
private void SyncPeople(Outlook.Application oApp, Outlook.Items oItems, string title, PersonCollection people) { DirectoryInfo cacheRoot = null; FileInfo cacheFile = null; // get image cache path if (ConfigurationManager.AppSettings["ImagePath"] != null) { cacheRoot = new DirectoryInfo(ConfigurationManager.AppSettings["ImagePath"]); } else { throw new ArenaApplicationException("'ImagePath' configuration file setting is not set"); } // Save the image to the cache file if (cacheRoot != null) { // if the root directory provided doesn't exist then create it if (!cacheRoot.Exists) { try { cacheRoot.Create(); } catch (System.Exception ex) { throw new ArenaApplicationException("Could not create '" + cacheRoot.FullName + "' directory!", ex); } } cacheFile = new FileInfo(cacheRoot.FullName + "\\TempSocsImage.jpg"); } Outlook.ContactItem oCt; foreach (Person person in people) { sbStatus.Text = "Syncing " + person.FullName + "..."; Application.DoEvents(); oCt = (Outlook.ContactItem)oItems.Find("[OrganizationalIDNumber] = " + person.PersonID.ToString()); if (oCt == null) { oCt = (Outlook.ContactItem)oApp.CreateItem(Outlook.OlItemType.olContactItem); } oCt.OrganizationalIDNumber = person.PersonID.ToString(); string categories = oCt.Categories; if (categories == null) { categories = string.Empty; } if (categories.IndexOf(title) < 0) { if (categories.Length > 0) { categories += "; "; } categories += title; oCt.Categories = categories; } oCt.FirstName = person.FirstName; oCt.LastName = person.LastName; if (!oCt.HasPicture || cbOverwritePicture.Checked) { if (person.Blob != null && person.Blob.ByteArray != null && person.Blob.ByteArray.Length > 0) { if (oCt.HasPicture) { oCt.RemovePicture(); } // delete the cache file if it exists (blob has been updated) if (cacheFile != null && cacheFile.Exists) { try { cacheFile.Delete(); } catch (System.Exception ex) { throw new ArenaApplicationException("Could not delete '" + cacheFile.FullName + "' file!", ex); } } // write cache file if (cacheFile != null) { FileStream fs = null; try { Image image = person.Blob.GetImage(0, 0); EncoderParameters eps = new EncoderParameters(1); eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); if (ici != null) { fs = cacheFile.OpenWrite(); image.Save(fs, ici, eps); } } catch (System.Exception ex) { throw new ArenaApplicationException("ArenaImage: Could not save cache file!", ex); } finally { if (fs != null) { fs.Close(); } } oCt.AddPicture(cacheFile.FullName); } } } foreach (PersonPhone phone in person.Phones) { switch (phone.PhoneType.Value) { case "Main/Home": oCt.HomeTelephoneNumber = phone.Number; break; case "Internal Phone": oCt.BusinessTelephoneNumber = phone.Number; break; case "Personal": oCt.Home2TelephoneNumber = phone.Number; break; case "FAX": oCt.BusinessFaxNumber = phone.Number; break; case "Messages": oCt.CallbackTelephoneNumber = phone.Number; break; case "Pager": oCt.PagerNumber = phone.Number; break; case "Cell": oCt.MobileTelephoneNumber = phone.Number; break; case "Other Phone 1": oCt.OtherTelephoneNumber = phone.Number; break; case "Home Fax": oCt.HomeFaxNumber = phone.Number; break; case "alpha pager": oCt.PagerNumber = phone.Number; break; case "Voice mail": oCt.CallbackTelephoneNumber = phone.Number; break; } } foreach (PersonAddress address in person.Addresses) { switch (address.AddressType.Value) { case "Main/Home Address": oCt.HomeAddressStreet = address.Address.StreetLine1; oCt.HomeAddressCity = address.Address.City; oCt.HomeAddressState = address.Address.State; oCt.HomeAddressPostalCode = address.Address.PostalCode; break; default: oCt.OtherAddressStreet = address.Address.StreetLine1; oCt.OtherAddressCity = address.Address.City; oCt.OtherAddressState = address.Address.State; oCt.OtherAddressPostalCode = address.Address.PostalCode; break; } } if (person.Emails.Active.Count > 0) { oCt.Email1Address = person.Emails.Active[0].Email; oCt.Email1DisplayName = person.FullName; } switch (person.Gender) { case Gender.Female: oCt.Gender = Outlook.OlGender.olFemale; break; case Gender.Male: oCt.Gender = Outlook.OlGender.olMale; break; default: oCt.Gender = Outlook.OlGender.olUnspecified; break; } oCt.NickName = person.NickName; oCt.Save(); } oCt = null; }