public OutlookFolder(MAPIFolder mapiFolder) : base(mapiFolder.Name) { if (mapiFolder == null) throw new ArgumentNullException("mapiFolder"); MapiFolder = mapiFolder; }
public MailFolderMounter(Application outlookApplication, string personalFoldersFile) { m_outlookApplication = outlookApplication; NameSpace ns = m_outlookApplication.Session; Folders AllFolders = ns.Folders; using (new ComObjectGovernor(ns)) using (new ComObjectGovernor(AllFolders)) { try { ETFolder = AllFolders["EAT Test Folders"]; } catch // throws if it doesn't exist and it is not meant to exist yet { ETFolder = null; } if (null != ETFolder) // Probably a dropping left by an old test ns.RemoveStore(ETFolder); ns.AddStoreEx(personalFoldersFile, OlStoreType.olStoreDefault); ETFolder = AllFolders["EAT Test Folders"]; if (null == ETFolder) throw new System.Exception("Test folder not added - Please name it 'EAT Test Folders' to ensure it is managed correctly in these tests"); } }
/* public static ResultadoTransaccion EnviarHTmlEmail(string toValue, string subjectValue, string bodyValue) { ResultadoTransaccion res = new ResultadoTransaccion(); try { oApp = new Application(); oNameSpace = oApp.GetNamespace("MAPI"); oOutboxFolder = oNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderSentMail); _MailItem oMailItem = (_MailItem)oApp.CreateItem(OlItemType.olMailItem); oMailItem.To = toValue; oMailItem.Subject = subjectValue; if (oMailItem.HTMLBody.IndexOf("</BODY>") > -1) oMailItem.HTMLBody = oMailItem.HTMLBody.Replace("</BODY>", bodyValue); oMailItem.SaveSentMessageFolder = oOutboxFolder; oMailItem.BodyFormat = OlBodyFormat.olFormatHTML; oMailItem.Send(); res.Estado = Enums.EstadoTransaccion.Aceptada; } catch (Exception ex) { res.Descripcion = ex.Message; res.Estado = Enums.EstadoTransaccion.Rechazada; Log.EscribirLog(ex.Message); } return res; } */ /// <summary> /// Metodo para el envio de Email desde el Modulo Calendario /// </summary> /// <param name="toValue">Email del receptor</param> /// <param name="subjectValue">Asunto del Email</param> /// <param name="bodyValue">Cuerpo del Email</param> public static ResultadoTransaccion EnviarEmail(string toValue, string subjectValue, string bodyValue) { ResultadoTransaccion res = new ResultadoTransaccion(); try { oApp = new Application(); oNameSpace = oApp.GetNamespace("MAPI"); oOutboxFolder = oNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderSentMail); _MailItem oMailItem = (_MailItem)oApp.CreateItem(OlItemType.olMailItem); oMailItem.To = toValue; oMailItem.Subject = subjectValue; oMailItem.Body = bodyValue; oMailItem.SaveSentMessageFolder = oOutboxFolder; oMailItem.BodyFormat = OlBodyFormat.olFormatRichText; oMailItem.Send(); res.Estado = Enums.EstadoTransaccion.Aceptada; } catch (Exception ex) { res.Descripcion = ex.Message; res.Estado = Enums.EstadoTransaccion.Rechazada; Log.EscribirLog(ex.Message); } return res; }
private static void GetFolders(MAPIFolder folder) { if (folder.Folders.Count == 0) { //Console.WriteLine(folder.FullFolderPath); string djb = folder.FullFolderPath.ToString(); //Console.WriteLine("djb: " + djb); if (djb.Length > 4) { if (djb.Substring(djb.LastIndexOf("\\") + 1) == Folder_Name) { mapifolder = folder; Console.WriteLine("Folder name match: " + Folder_Name); } } } else { foreach (MAPIFolder subFolder in folder.Folders) { GetFolders(subFolder); //Console.WriteLine(subFolder.FullFolderPath); // subFolder has a count of 16 items; the first two subtrees are ignored } } }
public OutlookCalendar() { // Create the Outlook application. Application oApp = new Application(); // Get the NameSpace and Logon information. // Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("mapi"); NameSpace oNS = oApp.GetNamespace("mapi"); //Log on by using a dialog box to choose the profile. oNS.Logon("", "", true, true); //Alternate logon method that uses a specific profile. // If you use this logon method, // change the profile name to an appropriate value. //oNS.Logon("YourValidProfile", Missing.Value, false, true); // Get the Calendar folder. UseOutlookCalendar = oNS.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); //Show the item to pause. //oAppt.Display(true); // Done. Log off. oNS.Logoff(); }
public ConversationTracking(IMailSelector selection) { _outlookApplication = new Application(); _ns = _outlookApplication.GetNamespace("MAPI"); _sent = _ns.GetDefaultFolder(OlDefaultFolders.olFolderSentMail); _selection = selection; Logger.LogInfo("EMAILTRACKING: Initialised Conversation Tracking"); }
static void DeleteEmptyFolders(MAPIFolder parentFolder) { foreach (MAPIFolder childFolder in parentFolder.Folders) { DeleteEmptyFolders(childFolder); } if (parentFolder.Items.Count == 0 && parentFolder.Folders.Count == 0) { Console.WriteLine(parentFolder.FullFolderPath); parentFolder.Delete(); } }
public void Connect() { oApp = OutlookCalendar.AttachToOutlook(); log.Debug("Setting up Outlook connection."); // Get the NameSpace and Logon information. NameSpace oNS = oApp.GetNamespace("mapi"); //Log on by using a dialog box to choose the profile. //oNS.Logon("", Type.Missing, true, true); //Implicit logon to default profile, with no dialog box //If 1< profile, a dialogue is forced unless implicit login used exchangeConnectionMode = oNS.ExchangeConnectionMode; if (exchangeConnectionMode != OlExchangeConnectionMode.olNoExchange) { log.Info("Exchange server version: " + oNS.ExchangeMailboxServerVersion.ToString()); } //Logon using a specific profile. Can't see a use case for this when using OGsync //If using this logon method, change the profile name to an appropriate value: //HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles //oNS.Logon("YourValidProfile", Type.Missing, false, true); log.Info("Exchange connection mode: " + exchangeConnectionMode.ToString()); currentUserSMTP = GetRecipientEmail(oNS.CurrentUser); currentUserName = oNS.CurrentUser.Name; if (currentUserName == "Unknown") { log.Info("Current username is \"Unknown\""); if (Settings.Instance.AddAttendees) { System.Windows.Forms.MessageBox.Show("It appears you do not have an Email Account configured in Outlook.\r\n" + "You should set one up now (Tools > Email Accounts) to avoid problems syncing meeting attendees.", "No Email Account Found", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); } } //Get the accounts configured in Outlook accounts = oNS.Accounts; // Get the Calendar folders useOutlookCalendar = getDefaultCalendar(oNS); if (MainForm.Instance.IsHandleCreated) { //resetting connection, so pick up selected calendar from GUI dropdown //***This might be cross thread, so don't rely on MainForm MainForm.Instance.cbOutlookCalendars.DataSource = new BindingSource(calendarFolders, null); KeyValuePair<String, MAPIFolder> calendar = (KeyValuePair<String, MAPIFolder>)MainForm.Instance.cbOutlookCalendars.SelectedItem; calendar = (KeyValuePair<String, MAPIFolder>)MainForm.Instance.cbOutlookCalendars.SelectedItem; useOutlookCalendar = calendar.Value; } // Done. Log off. oNS.Logoff(); }
private MAPIFolder GetFolder(MAPIFolder parentFolder, FolderPathNavigator folderPathNavigator) { if (folderPathNavigator.IsAtLastFolder()) return parentFolder; folderPathNavigator.Next(); foreach (MAPIFolder folder in parentFolder.Folders) { if (folder.FullFolderPath == folderPathNavigator.CurrentFolderPath) { return GetFolder(folder, folderPathNavigator); } } return null; }
private OutlookImportManager() { initialize(); if (_outlookApplication == null) return; _contactsFolder = _outlookApplication.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts); _importWorker = new BackgroundWorker(); _importWorker.WorkerReportsProgress = true; _importWorker.DoWork += onImportWorkerOnDoWork; _importWorker.RunWorkerCompleted += onImportWorkerOnRunWorkerCompleted; _importWorker.ProgressChanged += onImportWorkerOnProgressChanged; }
public void Connect() { oApp = OutlookCalendar.AttachToOutlook(); log.Debug("Setting up Outlook connection."); // Get the NameSpace and Logon information. NameSpace oNS = oApp.GetNamespace("mapi"); //Implicit logon to default profile, with no dialog box //If 1< profile, a dialogue is forced unless implicit login used exchangeConnectionMode = oNS.ExchangeConnectionMode; if (exchangeConnectionMode != OlExchangeConnectionMode.olNoExchange) { log.Info("Exchange server version: Unknown"); } log.Info("Exchange connection mode: " + exchangeConnectionMode.ToString()); currentUserSMTP = GetRecipientEmail(oNS.CurrentUser); currentUserName = oNS.CurrentUser.Name; if (currentUserName == "Unknown") { log.Info("Current username is \"Unknown\""); if (Settings.Instance.AddAttendees) { System.Windows.Forms.MessageBox.Show("It appears you do not have an Email Account configured in Outlook.\r\n" + "You should set one up now (Tools > Email Accounts) to avoid problems syncing meeting attendees.", "No Email Account Found", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); } } // Get the Calendar folders useOutlookCalendar = getDefaultCalendar(oNS); if (MainForm.Instance.IsHandleCreated) { //resetting connection, so pick up selected calendar from GUI dropdown MainForm.Instance.cbOutlookCalendars.DataSource = new BindingSource(calendarFolders, null); KeyValuePair<String, MAPIFolder> calendar = (KeyValuePair<String, MAPIFolder>)MainForm.Instance.cbOutlookCalendars.SelectedItem; calendar = (KeyValuePair<String, MAPIFolder>)MainForm.Instance.cbOutlookCalendars.SelectedItem; useOutlookCalendar = calendar.Value; } // Done. Log off. oNS.Logoff(); }
public bool Move(string targetfolder) { var outlookApplication = CreateOutlookInstance(); if (outlookApplication.ActiveExplorer() == null) { Log.Warning("Outlook not running!"); return(false); } var oNS = outlookApplication.GetNamespace("MAPI"); foreach (MAPIFolder folder in oNS.Folders) { MAPIFolder mfolder = GetFolder(folder, targetfolder); if (mfolder != null) { mailItem.Move(mfolder); return(true); } } Log.Error("Fail locating " + targetfolder); return(false); }
/// <summary> /// Method that is called for initialization. It checks if all necessary items for the monthly report /// are present in the current outlook account. If those items are not present, they are created. /// </summary> /// <param name="currentExplorer">The current explorer</param> public void CheckRequirements(Explorer currentExplorer) { // create the contracts and month sheet folders var primaryNotes = currentExplorer.Session.GetDefaultFolder(OlDefaultFolders.olFolderNotes); this.ContractsFolder = OutlookHelper.CreateOrGetFolder(primaryNotes, ContractsName, OlDefaultFolders.olFolderNotes); this.MonthSheetsFolder = OutlookHelper.CreateOrGetFolder(primaryNotes, MonthSheetsName, OlDefaultFolders.olFolderNotes); // Create Field in Contracts Folder OutlookHelper.CreateOrGetProperty(this.ContractsFolder, "Startdatum", OlUserPropertyType.olDateTime); OutlookHelper.CreateOrGetProperty(this.ContractsFolder, "Enddatum", OlUserPropertyType.olDateTime); OutlookHelper.CreateOrGetProperty(this.ContractsFolder, "Wöchenliche Arbeitszeit", OlUserPropertyType.olNumber); OutlookHelper.CreateOrGetProperty(this.ContractsFolder, "Urlaubstage", OlUserPropertyType.olNumber); OutlookHelper.CreateOrGetProperty(this.ContractsFolder, "Startsaldo", OlUserPropertyType.olNumber); // Create Field in MonthSheets Folder OutlookHelper.CreateOrGetProperty(this.MonthSheetsFolder, "Monat", OlUserPropertyType.olText); OutlookHelper.CreateOrGetProperty(this.MonthSheetsFolder, "Soll", OlUserPropertyType.olNumber); OutlookHelper.CreateOrGetProperty(this.MonthSheetsFolder, "Ist", OlUserPropertyType.olNumber); OutlookHelper.CreateOrGetProperty(this.MonthSheetsFolder, "Saldo", OlUserPropertyType.olNumber); OutlookHelper.CreateOrGetProperty(this.MonthSheetsFolder, "Urlaub genommen", OlUserPropertyType.olNumber); OutlookHelper.CreateOrGetProperty(this.MonthSheetsFolder, "Resturlaub", OlUserPropertyType.olNumber); }
/// <summary> /// Handles non-unique calendar names by recursively adding parent folders to the name /// </summary> /// <param name="name">Name/path of calendar (dictionary key)</param> /// <param name="folder">The target folder (dictionary value)</param> /// <param name="parentFolder">Recursive parent folder - leave null on initial call</param> private void calendarFolderAdd(String name, MAPIFolder folder, MAPIFolder parentFolder = null) { try { calendarFolders.Add(name, folder); } catch (System.ArgumentException ex) { if (OGCSexception.GetErrorCode(ex) == "0x80070057") { //An item with the same key has already been added. //Let's recurse up to the parent folder, looking to make it unique object parentObj = (parentFolder != null ? parentFolder.Parent : folder.Parent); if (parentObj is NameSpace) { //We've traversed all the way up the folder path to the root and still not unique log.Warn("MAPIFolder " + name + " does not have a unique name - so cannot use!"); } else if (parentObj is MAPIFolder) { String parentFolderName = (parentObj as MAPIFolder).FolderPath.Split('\\').Last(); calendarFolderAdd(System.IO.Path.Combine(parentFolderName, name), folder, parentObj as MAPIFolder); } } } }
private static void AddUnExistContactFromPST() { MAPIFolder folder = outlook.GetNamespace("MAPI").GetDefaultFolder(OlDefaultFolders.olFolderContacts); foreach (ContactItem nc in newData) { bool isExist = false; foreach (ContactItem oc in oldData) { if (oc.Email1Address.Equals(nc.Email1Address)) { isExist = true; break; } } if (!isExist) { ContactItem tc = nc.Copy(); tc.Move(folder); tc.Save(); } } }
private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar) { log.Debug("Finding default Mailbox calendar folders"); try { Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged -= Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged; Forms.Main.Instance.rbOutlookDefaultMB.Checked = true; Settings.Instance.OutlookService = OutlookOgcs.Calendar.Service.DefaultMailbox; Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged += Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged; defaultCalendar = oNS.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); calendarFolders.Add("Default " + defaultCalendar.Name, defaultCalendar); string excludeDeletedFolder = folders.Application.Session.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems).EntryID; Forms.Main.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.Yellow; Forms.Main.Instance.lOutlookCalendar.Text = "Getting calendars"; findCalendars(((MAPIFolder)defaultCalendar.Parent).Folders, calendarFolders, excludeDeletedFolder, defaultCalendar); Forms.Main.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.White; Forms.Main.Instance.lOutlookCalendar.Text = "Select calendar"; } catch (System.Exception ex) { OGCSexception.Analyse(ex, true); throw ex; } }
private void BuildFoldersTree(MAPIFolder folder, TreeNode rootNode) { if (folder.DefaultItemType == OlItemType.olMailItem) { TreeNode nodeitem = new TreeNode(folder.Name); nodeitem.Checked = true; nodeitem.Tag = folder.EntryID; if (rootNode == null) { tvOutlookFolders.Nodes.Add(nodeitem); } else { rootNode.Nodes.Add(nodeitem); } Folders subfolders = folder.Folders; foreach (Folder subfolder in subfolders) { BuildFoldersTree(subfolder, nodeitem); } } }
/// <summary> /// /// </summary> /// <param name="emailaddress"></param> /// <returns></returns> public static ContactItem getMatchingContactByEmail(MAPIFolder folder, String emailaddress) { foreach (Object item in folder.Items) { if (item is ContactItem) { ContactItem theItem = item as ContactItem; if ((theItem.Email1Address != String.Empty && theItem.Email1Address == emailaddress) || (theItem.Email2Address != String.Empty && theItem.Email1Address == emailaddress) || (theItem.Email3Address != String.Empty && theItem.Email1Address == emailaddress)) { return(theItem); } } else // The folder can only include certain type of items. { return(null); } } return(null); }
public static void AddItemCalendar(List <BirthdayItem> listItem, int hour_begin, int min_begin, int duration, int remind_min) { Application Application = null; Application = new Application(); MAPIFolder primaryCalendar = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); foreach (var item in listItem) { //var personalCalendar = primaryCalendar.Folders["Birthday"]; //if (personalCalendar == null) return; AppointmentItem newEvent = primaryCalendar.Items.Add(OlItemType.olAppointmentItem) as AppointmentItem; //AppointmentItem newEvent = personalCalendar.Items.Add(OlItemType.olAppointmentItem) as AppointmentItem; if (newEvent != null) { var date = new DateTime(DateTime.Now.Year, item.Birthday.Month, item.Birthday.Day, hour_begin, min_begin, 0); newEvent.Start = date; //newEvent.End = item.EndDateTime; var recur = newEvent.GetRecurrencePattern(); recur.RecurrenceType = OlRecurrenceType.olRecursYearly; recur.PatternStartDate = date; recur.StartTime = date; recur.Duration = duration; recur.NoEndDate = true; //recur.EndTime = DateTime.Now.AddMinutes(10); newEvent.ReminderMinutesBeforeStart = remind_min; newEvent.Subject = $"[B] День рождения {item.Name}"; newEvent.Body = $"День рождения {item.Name}. Дата рождения {item.Birthday:d}"; newEvent.Save(); AddProcProgressBar?.Invoke(null, null); } } Application.ActiveExplorer().CurrentFolder.Display(); }
public static Items GetAppointmentsInRange(String calendarName, DateTime startDate, DateTime endDate) { MAPIFolder calFolder = m_calendars[calendarName]; string filter = "[Start] >= '" + startDate.ToString("g") + "' AND [End] <= '" + endDate.ToString("g") + "' AND [AllDayEvent] = True"; Debug.WriteLine(filter); Items calItems = null; Items restrictItems = null; try { calItems = calFolder.Items; calItems.IncludeRecurrences = true; calItems.Sort("[Start]", Type.Missing); restrictItems = calItems.Restrict(filter); if (restrictItems.Count > 0) { return(restrictItems); } return(null); } catch (System.Exception) { if (restrictItems != null) { Marshal.ReleaseComObject(restrictItems); } return(null); } finally { if (calItems != null) { Marshal.ReleaseComObject(calItems); } } }
public static Dictionary <string, Model.Contact> RetreiveAllContact(bool accessEmal) { Application outLook = new Application(); NameSpace outLookNS = outLook.GetNamespace("MAPI"); MAPIFolder cf = outLookNS.GetDefaultFolder(OlDefaultFolders.olFolderContacts); Items ctcItems = cf.Items; Dictionary <string, Model.Contact> contacts = new Dictionary <string, CommonLibrary.Model.Contact>(); for (int j = 1; j < (ctcItems.Count + 1); j++) { ContactItem ctc = (ContactItem)ctcItems[j]; Model.Contact contact = new CommonLibrary.Model.Contact(); contact.FullName = ctc.FullName.ToString(); contact.Address = ctc.HomeAddress == null? "" : ctc.HomeAddress.ToString(); contact.HomePhone = ctc.HomeTelephoneNumber == null? "" : ctc.HomeTelephoneNumber.ToString(); contact.MobilePhone = ctc.MobileTelephoneNumber == null? "" : ctc.MobileTelephoneNumber.ToString(); if (accessEmal) { contact.Email = ctc.Email1Address == null ? "" : ctc.Email1Address.ToString(); } contact.BusinessPhone = ctc.BusinessTelephoneNumber == null ? "" : ctc.BusinessTelephoneNumber.ToString(); contact.BusinessFax = ctc.BusinessFaxNumber == null ? "" : ctc.BusinessFaxNumber.ToString(); contact.IPPhone = ""; if (!contacts.ContainsKey(contact.FullName)) { contacts.Add(contact.FullName, contact); } } return(contacts); }
private void getDefaultCalendar(NameSpace oNS, ref MAPIFolder defaultCalendar) { log.Debug("Finding default Mailbox calendar folders"); try { SettingsStore.Calendar profile = Settings.Profile.InPlay(); Boolean updateGUI = profile.Equals(Forms.Main.Instance.ActiveCalendarProfile); if (updateGUI) { Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged -= Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged; Forms.Main.Instance.rbOutlookDefaultMB.Checked = true; } profile.OutlookService = OutlookOgcs.Calendar.Service.DefaultMailbox; if (updateGUI) { Forms.Main.Instance.rbOutlookDefaultMB.CheckedChanged += Forms.Main.Instance.rbOutlookDefaultMB_CheckedChanged; } defaultCalendar = oNS.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); calendarFolders.Add("Default " + defaultCalendar.Name, defaultCalendar); string excludeDeletedFolder = folders.Application.Session.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems).EntryID; if (updateGUI) { Forms.Main.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.Yellow; Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.lOutlookCalendar, "Text", "Getting calendars"); } findCalendars(((MAPIFolder)defaultCalendar.Parent).Folders, calendarFolders, excludeDeletedFolder, defaultCalendar); if (updateGUI) { Forms.Main.Instance.lOutlookCalendar.BackColor = System.Drawing.Color.White; Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.lOutlookCalendar, "Text", "Select calendar"); } } catch (System.Exception ex) { OGCSexception.Analyse(ex, true); throw; } }
private Action <MailItem, string>[] GetActions() { Action <MailItem, string>[] resultAction = new Action <MailItem, string> [ResultingAction.Length]; for (int actionIndex = 0; actionIndex < ResultingAction.Length; actionIndex++) { RuleAction ruleAction = ResultingAction[actionIndex]; switch (ruleAction) { case RuleAction.ProcessPDF: resultAction[actionIndex] = (mail, a) => { _processor.ProcessMailItem(mail); }; break; case RuleAction.MoveToFolder: resultAction[actionIndex] = (mail, a) => { try { MAPIFolder folder = (MAPIFolder)_app.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Parent; folder = folder.Folders[a]; mail.Move(folder); } catch { } }; break; default: resultAction[actionIndex] = (mail, a) => { }; break; } } return(resultAction); }
/// <summary> /// Fetches all calendar events for a user falling within the provided range. /// </summary> /// <param name="from">Start search date.</param> /// <param name="to">End search dat.</param> /// <param name="username">User's calendar to search.</param> /// <returns></returns> public List<AppData> GetEventsInRange(DateTime from, DateTime to, string username) { List<AppData> appointments = new List<AppData>(); try { Recipient teamMember = _app.Session.CreateRecipient(username); MAPIFolder sharedCalendar = _app.Session.GetSharedDefaultFolder(teamMember, OlDefaultFolders.olFolderCalendar); if (sharedCalendar.DefaultMessageClass != "IPM.Appointment" || teamMember.DisplayType != 0) { return null; //Calendar not shared. } string sFilter = $"[End] > '{from:g}' AND [Start] < '{to:g}' AND [Recurring] = 'No'"; Items results = sharedCalendar.Items.Restrict(sFilter); for (int i = results.Count; i > 0; i--) { appointments.Add(new AppData(results[i], username)); } return appointments; } catch (COMException) { return null; } }
public void MonitorIncomingEmail(string mailBoxName, string folderName) { _space = _app.GetNamespace("MAPI"); //get root folder entry id if (!GetFolderEntryByName(mailBoxName, _space, out var rootEntry)) { throw new ArgumentException($"root folder {mailBoxName} cant be found"); } //get folder entry id if (!GetFolderEntryID(folderName, _space.GetFolderFromID(rootEntry), out var entryId)) { throw new ArgumentException($"folder {folderName} cant be found"); } _folder = _space.GetFolderFromID(entryId); if (_folder == null) { throw new ArgumentException($"folder entry {entryId} cant be found"); } _items = _folder.Items; _items.ItemAdd += Items_ItemAdd; }
private MAPIFolder FindConversationFolder(MAPIFolder folder) { if (folder.Name.Equals("Conversation History", StringComparison.OrdinalIgnoreCase)) { return(folder); } else { Folders childFolders = folder.Folders; if (childFolders.Count > 0) { foreach (MAPIFolder childFolder in childFolders) { MAPIFolder fol = FindConversationFolder(childFolder); if (fol != null) { return(fol); } } } return(null); } }
private Items GetAppointmentsInRange(MAPIFolder folder, DateTime startTime, DateTime endTime) { var filter = $"[Start] >= '{startTime:g}' and [Start] <= '{endTime:g}'"; try { Items calItems = folder.Items; calItems.IncludeRecurrences = true; calItems.Sort("[Start]", Type.Missing); Items restrictItems = calItems.Restrict(filter); if (restrictItems.Count > 0) { return(restrictItems); } else { return(null); } } catch (Exception ex) { return(null); } }
protected override void Execute(NativeActivityContext context) { var folder = Folder.Get(context); if (string.IsNullOrEmpty(folder)) { return; } var outlookApplication = CreateOutlookInstance(); if (outlookApplication.ActiveExplorer() == null) { Log.Warning("Outlook not running!"); return; } MAPIFolder inBox = (MAPIFolder)outlookApplication.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox); MAPIFolder folderbase = inBox.Store.GetRootFolder(); MAPIFolder mfolder = GetFolder(folderbase, folder); Items Items = mfolder.Items; var unreadonly = UnreadOnly.Get(context); if (unreadonly) { var Filter = "[Unread]=true"; // var Filter = "@SQL=" + (char)34 + "urn:schemas:httpmail:hasattachment" + (char)34 + "=1 AND " + // var Filter = "@SQL=" + (char)34 + "urn:schemas:httpmail:read" + (char)34 + "=0"; Items.Restrict(Filter); } var result = new List <email>(); foreach (var folderItem in Items) { Microsoft.Office.Interop.Outlook.MailItem mailItem = folderItem as Microsoft.Office.Interop.Outlook.MailItem; if (mailItem != null) { var _e = new email(mailItem); if (unreadonly) { if (_e.UnRead) { result.Add(_e); } } else { result.Add(_e); } } } Emails.Set(context, result); IEnumerator <email> _enum = result.ToList().GetEnumerator(); context.SetValue(_elements, _enum); bool more = _enum.MoveNext(); if (more) { context.ScheduleAction(Body, _enum.Current, OnBodyComplete); } }
public ConversationNavigator(Application app, MAPIFolder folder) : base(app, folder) { }
public static List <OutlookEmails> ReadMailItems() { Application outlookapplication = null; NameSpace outlookNamespace = null; MAPIFolder inboxFolder = null; Items mailItems = null; List <OutlookEmails> listEmailDetails = new List <OutlookEmails>(); OutlookEmails emailDetails; try { outlookapplication = new Application(); outlookNamespace = outlookapplication.GetNamespace("MAPI"); inboxFolder = outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox); mailItems = inboxFolder.Items; ProgressBar pBar1 = new ProgressBar(); pBar1.Minimum = 1; pBar1.Maximum = mailItems.Count; pBar1.Value = 1; pBar1.Step = 1; Form1 pbarForm = new Form1(); pBar1.Width = 677; pbarForm.Controls.Add(pBar1); pbarForm.StartPosition = FormStartPosition.CenterScreen; pbarForm.Show(); for (int j = 1; j < mailItems.Count; j++) { emailDetails = new OutlookEmails(); emailDetails.EmailSubject = mailItems[j].Subject; emailDetails.RecievedOn = mailItems[j].ReceivedTime; if (mailItems[j].senderEmailType == "EX") { emailDetails.EmailFrom = "xyz.de"; } if (mailItems[j].senderEmailType == "SMTP") { string after = "@"; string x = mailItems[j].SenderEmailAddress; string final = x.Substring(x.LastIndexOf(after) + 1); emailDetails.EmailFrom = final.ToLower(); } listEmailDetails.Add(emailDetails); pBar1.PerformStep(); } System.Threading.Thread.Sleep(2); pbarForm.Close(); } catch (System.Exception ex) { Console.WriteLine(ex.Message); } finally { ReleaseComObject(mailItems); ReleaseComObject(inboxFolder); ReleaseComObject(outlookNamespace); ReleaseComObject(outlookapplication); } return(listEmailDetails); }
public void GetReportItemsData(List <ReportItem> aReportItemList, MAPIFolder aProcessedFolder, MAPIFolder aExceptionFolder) { foreach (ReportItem myitem in aReportItemList) { OutlookItem myReportItem = new OutlookItem(); EmailProperties myEmailProperties = new EmailProperties(); try { //Assign Values myReportItem.EntryID = myitem.EntryID; myReportItem.FromSender = (String)myitem.PropertyAccessor.GetProperty(myEmailProperties.PR_SENT_REPRESENTING_SMTP_ADDRESS_W); myReportItem.ToReceiver = (String)myitem.PropertyAccessor.GetProperty(myEmailProperties.PR_DISPLAY_TO_W); myReportItem.EmailSubject = (String)myitem.PropertyAccessor.GetProperty(myEmailProperties.PR_ORIGINAL_SUBJECT_W); myReportItem.EmailBody = myitem.Body; //myReportItem.EmailBody = Encoding.UTF8.GetString(new UnicodeEncoding().GetBytes(myitem.Body)).Substring(0, 200); myReportItem.SubscriberNumber = myReportItem.GetMSISDN(myReportItem.EmailSubject, myReportItem.EmailBody); myReportItem.InvalidEmailID = null; myReportItem.AlgoType = "FZ"; myReportItem.TypeOfItem = "ReportItem"; myReportItem.HasAttachment = (Boolean)myitem.PropertyAccessor.GetProperty(myEmailProperties.PR_HASATTACH); myReportItem.EmailSize = myitem.Size; myReportItem.ReceiveAt = (DateTime)myitem.PropertyAccessor.GetProperty(myEmailProperties.PR_MESSAGE_DELIVERY_TIME); myReportItem.SentOn = (DateTime)myitem.PropertyAccessor.GetProperty(myEmailProperties.PR_ORIGINAL_SUBMIT_TIME); // Get Invalid ID from To List if (myReportItem.ToReceiver.Contains("@")) { myReportItem.InvalidEmailID = myReportItem.ToReceiver; myReportItem.AlgoType = "FA"; } //Display Some info Console.WriteLine(myReportItem.FromSender); Console.WriteLine(myReportItem.ToReceiver); Console.WriteLine(myReportItem.EmailSubject); //Insert Into database new Database().InsertIntoTable(myReportItem); //Move read items myitem.Move(aProcessedFolder); } catch (System.Exception ex) { Console.WriteLine(ex.Message); myitem.Move(aExceptionFolder); } } }
private void findCalendars(Folders folders, Dictionary <string, MAPIFolder> calendarFolders, String excludeDeletedFolder, MAPIFolder defaultCalendar = null) { //Initiate progress bar (red line underneath "Getting calendars" text) System.Drawing.Graphics g = Forms.Main.Instance.tabOutlook.CreateGraphics(); System.Drawing.Pen p = new System.Drawing.Pen(System.Drawing.Color.Red, 3); System.Drawing.Point startPoint = new System.Drawing.Point(Forms.Main.Instance.lOutlookCalendar.Location.X, Forms.Main.Instance.lOutlookCalendar.Location.Y + Forms.Main.Instance.lOutlookCalendar.Size.Height + 3); double stepSize = Forms.Main.Instance.lOutlookCalendar.Size.Width / folders.Count; int fldCnt = 0; foreach (MAPIFolder folder in folders) { fldCnt++; System.Drawing.Point endPoint = new System.Drawing.Point(Forms.Main.Instance.lOutlookCalendar.Location.X + Convert.ToInt16(fldCnt * stepSize), Forms.Main.Instance.lOutlookCalendar.Location.Y + Forms.Main.Instance.lOutlookCalendar.Size.Height + 3); try { g.DrawLine(p, startPoint, endPoint); } catch { /*May get GDI+ error if g has been repainted*/ } System.Windows.Forms.Application.DoEvents(); try { OlItemType defaultItemType = folder.DefaultItemType; if (defaultItemType == OlItemType.olAppointmentItem) { if (defaultCalendar == null || (folder.EntryID != defaultCalendar.EntryID)) { calendarFolderAdd(folder.Name, folder); } } if (folder.EntryID != excludeDeletedFolder && folder.Folders.Count > 0) { findCalendars(folder.Folders, calendarFolders, excludeDeletedFolder, defaultCalendar); } } catch (System.Exception ex) { OGCSexception.Analyse(ex); if (oApp.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") || OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115") { log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders."); Forms.Main.Instance.ToolTips.SetToolTip(Forms.Main.Instance.cbOutlookCalendars, "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected."); } else { log.Error("Failed to recurse MAPI folders."); log.Error(ex.Message); MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.", "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } p.Dispose(); try { g.Clear(System.Drawing.Color.White); } catch { } g.Dispose(); System.Windows.Forms.Application.DoEvents(); }
public void UseOutlookCalendar(MAPIFolder set) { useOutlookCalendar = set; }
public MailNavigator(Application app, MAPIFolder folder) { this.OutlookApp = app; this.Explorer =app.ActiveExplorer(); this.Folder = folder; if (Explorer.CurrentFolder == folder && Explorer.Selection.Count > 0) { this.Current = new OutlookItem(this.Explorer.Selection[1]); } else { MoveTOStart(); } }
/// <summary> /// Checks to see if the specified folder contains an appointment object, is so, we assume its a calendar /// so we should show the calendar buttons. /// </summary> /// <param name="oFolder"></param> private void ShowCalendarButtonsFor(MAPIFolder oFolder) { ShowCalendarButtons(oFolder.CurrentView.ViewType == OlViewType.olCalendarView); }
/* https://msdn.microsoft.com/en-us/library/office/gg619398.aspx*/ static Items GetOutlookAppointmentsInRange(MAPIFolder folder, DateTime startTime, DateTime endTime) { string filter = "[Start] >= '" + startTime.ToString("g") + "' AND [End] <= '" + endTime.ToString("g") + "'"; Items calItems = folder.Items; calItems.IncludeRecurrences = true; calItems.Sort("[Start]", Type.Missing); Items restrictItems = calItems.Restrict(filter); return restrictItems; }
public static IEnumerable <AppointmentItem> EnumerateOutlookAppointmentsActiveIn(this MAPIFolder calendarFolder, TimeInterval time) { var items = calendarFolder.Items; items.Sort("[Start]", Type.Missing); items.IncludeRecurrences = true; var q = String.Format($"[End] > {time.Begin.OutlookQueryFormat().Quote()}"); for ( var a = (AppointmentItem)items.Find(q); a != null && a.Start < time.End; a = (AppointmentItem)items.FindNext()) { yield return(a); } }
private void scanSubFolder(MAPIFolder folder) { return; Folders collectionSubFolder = folder.Folders; for (int i = 1; i <= collectionSubFolder.Count; i++) { MAPIFolder subFolder = collectionSubFolder[i]; object itemObj = null; for (int j = 1; j <= subFolder.Items.Count; j++) { itemObj = subFolder.Items[j]; FlagKpeopleMail(itemObj); } } }
protected virtual void Dispose(bool isDisposing) { Logger.LogInfo("EMAILTRACKING: Disposing Conversation Tracking - " + isDisposing); if (isDisposing) { GC.SuppressFinalize(this); } if (_ns != null) Marshal.ReleaseComObject(_ns); if (_sent != null) Marshal.ReleaseComObject(_sent); if (_outlookApplication != null) Marshal.ReleaseComObject(_outlookApplication); _ns = null; _sent = null; _outlookApplication = null; }
private void GetTaskLists(MAPIFolder searchFolder, List<OutlookFolder> outlookCalendars) { try { if (searchFolder == null) { return; } if (searchFolder.DefaultMessageClass == "IPM.Task" && searchFolder.DefaultItemType == OlItemType.olTaskItem) { //Add Calendar MAPIFolder to List outlookCalendars.Add(new OutlookFolder { Name = searchFolder.Name, EntryId = searchFolder.EntryID, StoreId = searchFolder.EntryID }); } if (searchFolder.Folders != null && searchFolder.Folders.Count > 0) { //Walk through all subFolders in MAPIFolder foreach (MAPIFolder subFolder in searchFolder.Folders) { //Get Calendar MAPIFolders GetTaskLists(subFolder, outlookCalendars); } } } catch (Exception exception) { Logger.Error(exception); } finally { if (searchFolder != null) { Marshal.FinalReleaseComObject(searchFolder); } } }
public dynamic Move(MAPIFolder DestFldr) { Utils.LogNotImplementedStackTrace(); return _item.Move(DestFldr); }
private void UpdateCustomFolder(MAPIFolder oFolder) { if (oFolder == null) return; try { // Remove old item (selectmenu+1) if (TrayMenu.Items.Contains(_customMenu)) { TrayMenu.Items.Remove(_customMenu); } string folderPath = GetFolderPath(GenerateFolderPathFromObject(oFolder)); OutlookViewControl.Folder = folderPath; // Save the EntryId and the StoreId for this folder in the preferences. Preferences.OutlookFolderEntryId = oFolder.EntryID; Preferences.OutlookFolderStoreId = oFolder.StoreID; Preferences.OutlookFolderName = folderPath; // store the custom folder details in memory as well, in case the user wants to switch back to it. _customFolderDefinition.OutlookFolderName = Preferences.OutlookFolderName; _customFolderDefinition.OutlookFolderStoreId = Preferences.OutlookFolderStoreId; _customFolderDefinition.OutlookFolderEntryId = Preferences.OutlookFolderEntryId; _customFolder = Preferences.OutlookFolderName; // Update the UI to reflect the new settings. TrayMenu.Items.Insert(GetSelectFolderMenuLocation() + 1, new ToolStripMenuItem(oFolder.Name, null, CustomFolderMenu_Click)); _customMenu = (ToolStripMenuItem)TrayMenu.Items[GetSelectFolderMenuLocation() + 1]; SetMAPIFolder(); CheckSelectedMenuItem(_customMenu); UpdateOutlookViewsList(); } catch (Exception) { MessageBox.Show(this, Resources.ErrorSettingFolder, Resources.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// /// </summary> /// <param name="oFolder"></param> /// <returns></returns> private static string GenerateFolderPathFromObject(MAPIFolder oFolder) { string fullFolderPath = "\\\\"; var subfolders = new List<string> { oFolder.Name }; while (oFolder != null && oFolder.Parent != null) { oFolder = oFolder.Parent as MAPIFolder; if (oFolder != null) subfolders.Add(oFolder.Name); } for (int i = subfolders.Count - 1; i >= 0; i--) { fullFolderPath += subfolders[i] + "\\"; } if (fullFolderPath.EndsWith("\\")) { fullFolderPath = fullFolderPath.Substring(0, fullFolderPath.Length - 1); } return fullFolderPath; }
public void Connect() { if (!OutlookOgcs.Calendar.InstanceConnect) { return; } OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: false); log.Debug("Setting up Outlook connection."); // Get the NameSpace and Logon information. NameSpace oNS = null; try { oNS = oApp.GetNamespace("mapi"); //Implicit logon to default profile, with no dialog box //If 1< profile, a dialogue is forced unless implicit login used exchangeConnectionMode = oNS.ExchangeConnectionMode; if (exchangeConnectionMode != OlExchangeConnectionMode.olNoExchange) { log.Info("Exchange server version: Unknown"); } log.Info("Exchange connection mode: " + exchangeConnectionMode.ToString()); oNS = GetCurrentUser(oNS); if (!Settings.Instance.OutlookGalBlocked && currentUserName == "Unknown") { log.Info("Current username is \"Unknown\""); if (Settings.Instance.AddAttendees) { System.Windows.Forms.MessageBox.Show("It appears you do not have an Email Account configured in Outlook.\r\n" + "You should set one up now (Tools > Email Accounts) to avoid problems syncing meeting attendees.", "No Email Account Found", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); } } log.Debug("Get the folders configured in Outlook"); folders = oNS.Folders; // Get the Calendar folders useOutlookCalendar = getCalendarStore(oNS); if (Forms.Main.Instance.IsHandleCreated) { log.Fine("Resetting connection, so re-selecting calendar from GUI dropdown"); Forms.Main.Instance.cbOutlookCalendars.SelectedIndexChanged -= Forms.Main.Instance.cbOutlookCalendar_SelectedIndexChanged; Forms.Main.Instance.cbOutlookCalendars.DataSource = new BindingSource(calendarFolders, null); //Select the right calendar int c = 0; foreach (KeyValuePair <String, MAPIFolder> calendarFolder in calendarFolders) { if (calendarFolder.Value.EntryID == Settings.Instance.UseOutlookCalendar.Id) { Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.cbOutlookCalendars, "SelectedIndex", c); } c++; } if ((int)Forms.Main.Instance.GetControlPropertyThreadSafe(Forms.Main.Instance.cbOutlookCalendars, "SelectedIndex") == -1) { Forms.Main.Instance.SetControlPropertyThreadSafe(Forms.Main.Instance.cbOutlookCalendars, "SelectedIndex", 0); } KeyValuePair <String, MAPIFolder> calendar = (KeyValuePair <String, MAPIFolder>)Forms.Main.Instance.GetControlPropertyThreadSafe(Forms.Main.Instance.cbOutlookCalendars, "SelectedItem"); useOutlookCalendar = calendar.Value; Forms.Main.Instance.cbOutlookCalendars.SelectedIndexChanged += Forms.Main.Instance.cbOutlookCalendar_SelectedIndexChanged; } OutlookOgcs.Calendar.Categories = null; } finally { // Done. Log off. if (oNS != null) { oNS.Logoff(); } oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS); } }
/// <summary> /// This will populate the _outlookFolder object with the MapiFolder for the EntryID and StoreId stored /// in the registry. /// </summary> private void SetMAPIFolder() { // Load up the MAPI Folder from Entry / Store IDs if (Preferences.OutlookFolderEntryId != "" && Preferences.OutlookFolderStoreId != "") { try { _outlookFolder = Startup.OutlookNameSpace.GetFolderFromID(Preferences.OutlookFolderEntryId, Preferences.OutlookFolderStoreId); ShowCalendarButtonsFor(_outlookFolder); } catch (Exception ex) { Logger.Error(ex, "Error setting MAPI folder."); } } else { _outlookFolder = null; } }
public void GetMailItemsData(List <MailItem> aMailItemList, MAPIFolder aProcessedFolder, MAPIFolder aExceptionFolder) { foreach (MailItem myitem in aMailItemList) { OutlookItem myMailItem = new OutlookItem(); EmailProperties myEmailProperties = new EmailProperties(); try { //Assign Values myMailItem.EntryID = myitem.EntryID; myMailItem.FromSender = myitem.SenderName; myMailItem.ToReceiver = myitem.To; myMailItem.EmailSubject = myitem.Subject; myMailItem.EmailBody = myitem.Body; //myMailItem.EmailBody = Encoding.UTF8.GetString(new UnicodeEncoding().GetBytes(myitem.Body)); //Get MSISDN from Subject or Body myMailItem.SubscriberNumber = myMailItem.GetMSISDN(myMailItem.EmailSubject, myMailItem.EmailBody); //Get Email ID from Body String[] SplitDataString = myMailItem.GetInvalidEmailID(myMailItem.EmailSubject, myMailItem.EmailBody).Split('|'); myMailItem.InvalidEmailID = (SplitDataString[0] == "") ? null : SplitDataString[0]; myMailItem.AlgoType = SplitDataString[1]; //myMailItem.InvalidEmailID = myMailItem.GetInvalidEmailID(myMailItem.EmailSubject, myMailItem.EmailBody).Split('|'); myMailItem.TypeOfItem = "MailItem"; myMailItem.HasAttachment = (Boolean)myitem.PropertyAccessor.GetProperty(myEmailProperties.PR_HASATTACH); myMailItem.EmailSize = myitem.Size; myMailItem.ReceiveAt = myitem.ReceivedTime; myMailItem.SentOn = myitem.SentOn; //Display Some Info Console.WriteLine(myMailItem.InvalidEmailID); Console.WriteLine(myMailItem.FromSender); Console.WriteLine(myMailItem.ToReceiver); Console.WriteLine(myMailItem.EmailSubject); //Insert Into Database new Database().InsertIntoTable(myMailItem); //Move read items myitem.Move(aProcessedFolder); } catch (System.Exception ex) { Console.WriteLine(ex.Message); myitem.Move(aExceptionFolder); } } }
/* public void Run(Outlook.MailItem mi) { String hdr = this.wrapper.GetOneProp(mi, CdoPR_TRANSPORT_MESSAGE_HEADERS).ToString(); String bdy = this.wrapper.GetOneProp(mi, CdoPR_BODY).ToString(); Console.WriteLine(hdr); Console.WriteLine(bdy); } */ public void resetAutotraining(Boolean enable, String new_folder_spam, String new_folder_ham) { try { this.logger.WriteLine("Resetting AutoTrain, enabled = " + enable); if (enable) { this.handleAutotrain(false); this.folder_spam = this.getFolderByName(new_folder_spam); this.folder_ham = this.getFolderByName(new_folder_ham); this.handleAutotrain(true); } else { this.handleAutotrain(false); } } catch (Exception ex) { this.logger.WriteError("resetAutotraining(" + enable + ", " + new_folder_spam + ", " + new_folder_ham + "): " + ex.Message); this.logger.WriteError(ex.StackTrace); } }
private void findCalendars(Folders folders, Dictionary<string, MAPIFolder> calendarFolders, MAPIFolder defaultCalendar) { string excludeDeletedFolder = folders.Application.Session.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems).EntryID; foreach (MAPIFolder folder in folders) { try { OlItemType defaultItemType = folder.DefaultItemType; if (defaultItemType == OlItemType.olAppointmentItem) { if (defaultCalendar == null || (folder.EntryID != defaultCalendar.EntryID)) calendarFolders.Add(folder.Name, folder); } if (folder.EntryID != excludeDeletedFolder && folder.Folders.Count > 0) { findCalendars(folder.Folders, calendarFolders, defaultCalendar); } } catch (System.Exception ex) { if (oApp.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") || ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.")) { log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders."); MainForm.Instance.ToolTips.SetToolTip(MainForm.Instance.cbOutlookCalendars, "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected."); } else { log.Error("Failed to recurse MAPI folders."); log.Error(ex.Message); MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.", "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } }
/// <summary> /// /// </summary> /// <param name="emailaddress"></param> /// <returns></returns> public static ContactItem getMatchingContactByEmail(MAPIFolder folder, String emailaddress) { foreach (Object item in folder.Items) { if (item is ContactItem) { ContactItem theItem = item as ContactItem; if ((theItem.Email1Address != String.Empty && theItem.Email1Address == emailaddress) || (theItem.Email2Address != String.Empty && theItem.Email1Address == emailaddress) || (theItem.Email3Address != String.Empty && theItem.Email1Address == emailaddress)) { return theItem; } } else // The folder can only include certain type of items. { return null; } } return null; }
//private void EnumerateFolders(Folder folder) //{ // foreach (Folder childFolder in folder.Folders) // { // try // { // // iterate through mails in this folder // Items mails = childFolder.Items; // foreach (object mail in childFolder.Items) // { // if (mail is MailItem) // { // var mailItem = mail as MailItem; // var senderName = mailItem.SenderName; // var senderEmailAddress = mailItem.SenderEmailAddress; // var senderCombo = senderName + "/" + senderEmailAddress; // if (senderEmailAddress is null) // continue; // if (DictSenderName.ContainsKey(senderName)) // { // DictSenderName[senderName] = DictSenderName[senderName] + 1; // } // else // { // DictSenderName.Add(senderName, 1); // } // if (DictSenderEmail.ContainsKey(senderEmailAddress)) // { // DictSenderEmail[senderEmailAddress] = DictSenderEmail[senderEmailAddress] + 1; // } // else // { // DictSenderEmail.Add(senderEmailAddress, 1); // } // if (DictSenderCombo.ContainsKey(senderCombo)) // { // DictSenderCombo[senderCombo] = DictSenderCombo[senderCombo] + 1; // } // else // { // DictSenderCombo.Add(senderCombo, 1); // } // } // } // } // catch (System.Exception ex) // { // // throw; // } // // Call EnumerateFolders using childFolder. // EnumerateFolders(childFolder); // } // // TODO: nicer user path from modelConfig // string userpath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // dt.Write(DictSenderName, userpath + "\\dict-sender-name.bin"); // dt.Write(DictSenderEmail, userpath + "\\dict-sender-email.bin"); // dt.Write(DictSenderCombo, userpath + "\\dict-sender-combo.bin"); //} public void CurrentExplorer_Event() { MAPIFolder selectedFolder = Application.ActiveExplorer().CurrentFolder; string expMessage = ""; // "Your current folder is " + selectedFolder.Name + ".\n"; string itemMessage = ""; // "Item is unknown."; try { if (Application.ActiveExplorer().Selection.Count > 0) { MailItem mailItem = Application.ActiveExplorer().Selection[1] as MailItem; if (mailItem != null) { try { // Show warning or close may open window var scoreResult = scoring.getSummary(mailItem); if (scoreResult.IsSuspicious) { VMInfoScreen.ShowScore(scoreResult); } else { VMInfoScreen.Close(); } tvcntr++; } catch (System.Exception ex) { Debug.Write(ex.StackTrace); } // remove finalfrontier p that are already present //int startpos = mailItem.HTMLBody.IndexOf("<p class=\"finalfrontier"); //int endpos = mailItem.HTMLBody.IndexOf("</p>"); //if (!startpos.Equals(-1)) mailItem.HTMLBody = mailItem.HTMLBody.Remove(startpos, endpos-startpos); //mailItem.HTMLBody = "<p class=\"finalfrontier\" style=\"background-color:red\"><b>FinalFrontier</b><br/>" + itemMessage + "</p>" + mailItem.HTMLBody; //mailItem.Display(false); } /* else if (selObject is Outlook.ContactItem) * { * Outlook.ContactItem contactItem = * (selObject as Outlook.ContactItem); * itemMessage = "The item is a contact." + * " The full name is " + contactItem.Subject + "."; * contactItem.Display(false); * } * else if (selObject is Outlook.AppointmentItem) * { * Outlook.AppointmentItem apptItem = * (selObject as Outlook.AppointmentItem); * itemMessage = "The item is an appointment." + * " The subject is " + apptItem.Subject + "."; * } * else if (selObject is Outlook.TaskItem) * { * Outlook.TaskItem taskItem = * (selObject as Outlook.TaskItem); * itemMessage = "The item is a task. The body is " + taskItem.Body + "."; + } + else if (selObject is Outlook.MeetingItem) + { + Outlook.MeetingItem meetingItem = + (selObject as Outlook.MeetingItem); + itemMessage = "The item is a meeting item. " + + "The subject is " + meetingItem.Subject + "."; + } */ expMessage = expMessage + itemMessage; } } catch (System.Exception ex) { expMessage = ex.Message; } //MessageBox.Show(expMessage); }
public static AppointmentItemWrapper CreateNewAppointmentForTesting(MAPIFolder calendarFolder, NameSpace mapiNamespace) { return(new AppointmentItemWrapper((AppointmentItem)calendarFolder.Items.Add(OlItemType.olAppointmentItem), entryId => (AppointmentItem)mapiNamespace.GetItemFromID(entryId, calendarFolder.StoreID))); }
public OutlookAdapter() { outlook = new Application(); nspace = outlook.GetNamespace("MAPI"); contactsFolder = nspace.GetDefaultFolder(OlDefaultFolders.olFolderContacts); }
public static MAPIFolder MarkedWorkSubfolder(string SeatGroupName) { MAPIFolder assignments = getSubFolder(OutlookProvider.sentItems, "marked"); return(getSubFolder(assignments, SeatGroupName)); }
public void RemoveStore(MAPIFolder Folder) { _nameSpace.RemoveStore(Folder); }
public static IList <AppointmentItem> GetOutlookAppointmentsActiveIn(this MAPIFolder calendarFolder, TimeInterval time) { return(calendarFolder.EnumerateOutlookAppointmentsActiveIn(time).ToList()); }
public ArchiveRibbon() { _outlook = new Application(); _archiveFolder = _outlook.Application.Session.DefaultStore.GetRootFolder().Folders[ArchiveFolderName]; }
public static IList <AppointmentItem> GetOutlookAppointments(this Application outlook, MAPIFolder calendarFolder, TimeInterval time) { calendarFolder.Items.Sort("[Start]", false); calendarFolder.Items.IncludeRecurrences = true; var q = String.Format("[Start] >= {0} And [End] < {1}", time.Begin.OutlookQueryFormat().Quote(), time.End.OutlookQueryFormat().Quote()); log.Info(q); var appointments = calendarFolder.Items.Restrict(q); return(appointments.OfType <AppointmentItem>().ToList()); }
private void UpdateFolder (MAPIFolder folder) { if (IsTaskSynchronizationEnabled) { if (folder.DefaultItemType != OlItemType.olAppointmentItem && folder.DefaultItemType != OlItemType.olTaskItem && folder.DefaultItemType != OlItemType.olContactItem) { string wrongFolderMessage = string.Format ("Wrong ItemType in folder '{0}'. It should be a calendar, task or contact folder.", folder.Name); MessageBox.Show (wrongFolderMessage, "Configuration Error"); return; } } else { if (folder.DefaultItemType != OlItemType.olAppointmentItem && folder.DefaultItemType != OlItemType.olContactItem) { string wrongFolderMessage = string.Format ("Wrong ItemType in folder '{0}'. It should be a calendar or contact folder.", folder.Name); MessageBox.Show (wrongFolderMessage, "Configuration Error"); return; } } _folderEntryId = folder.EntryID; _folderStoreId = folder.StoreID; _outoookFolderNameTextBox.Text = folder.Name; _folderType = folder.DefaultItemType; OnHeaderChanged(); }