/// <summary> /// Initializes the OutLook application and retrieves the meetings scheduled for current day. /// For logging into OutLook, we need the profile name. Default profile name is extracted from registry settings. /// </summary> private void InitializeMeetingDuration() { try { if (!Process.GetProcessesByName("OUTLOOK").Any()) { return; } outlookApplication = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application; nameSpace = outlookApplication.GetNamespace("mapi"); var profile = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles", "DefaultProfile", null); nameSpace.Logon(profile.ToString(), Missing.Value, true, true); fldCalander = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder; fldDeletedItems = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDeletedItems) as Outlook.Folder; items = GetAppointmentsInRange(fldCalander); fldCalander.BeforeItemMove += fldCalander_BeforeItemMove; items.ItemAdd += Items_ItemAdd; items.ItemChange += Items_ItemChange; if (items != null) { foreach (Outlook.AppointmentItem oAppt in items) { meetings.Add(oAppt.GlobalAppointmentID, new MeetingDetails(oAppt.Start, oAppt.End, oAppt.Duration)); } } } catch (Exception ex) { log.Error(ex.ToString()); } }
// outlook work private OutLook.MAPIFolder searchFolder(string folderName) { OutLook.NameSpace nameSpace = OutLookApp.GetNamespace("MAPI"); OutLook.Folders inboxSubfolders = Folder_Contacts.Folders; for (int i = 1; inboxSubfolders.Count >= i; i++) { OutLook.MAPIFolder subfolderInbox = inboxSubfolders[i]; if (subfolderInbox.Name == folderName) { try { return(subfolderInbox); } catch (COMException exception) { System.Windows.Forms.MessageBox.Show(exception.Message); } } if (subfolderInbox != null) { Marshal.ReleaseComObject(subfolderInbox); } } if (inboxSubfolders != null) { Marshal.ReleaseComObject(inboxSubfolders); } if (nameSpace != null) { Marshal.ReleaseComObject(nameSpace); } return(null); }
public static int Main(string[] args) { try { // Create the Outlook application. Outlook.Application oApp = new Outlook.Application(); // Get the NameSpace and Logon information. // Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("mapi"); Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); //Log on by using a dialog box to choose the profile. oNS.Logon(Missing.Value, Missing.Value, true, true); //Alternate logon method that uses a specific profile. // TODO: 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. Outlook.MAPIFolder oCalendar = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); // Get the Items (Appointments) collection from the Calendar folder. Outlook.Items oItems = oCalendar.Items; // Get the first item. Outlook.AppointmentItem oAppt = (Outlook.AppointmentItem)oItems.GetFirst(); // Show some common properties. Console.WriteLine("Subject: " + oAppt.Subject); Console.WriteLine("Organizer: " + oAppt.Organizer); Console.WriteLine("Start: " + oAppt.Start.ToString()); Console.WriteLine("End: " + oAppt.End.ToString()); Console.WriteLine("Location: " + oAppt.Location); Console.WriteLine("Recurring: " + oAppt.IsRecurring); //Show the item to pause. oAppt.Display(true); // Done. Log off. oNS.Logoff(); // Clean up. oAppt = null; oItems = null; oCalendar = null; oNS = null; oApp = null; } //Simple error handling. catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } //Default return value return(0); }
//check if features submitted private string AreFeatureSubmitted() { string featuresURL = Properties.Settings.Default.ServerURL + "checkEmailInFeaturesServlet.check?email=" + Globals.ThisAddIn.myCredentials.EmailID; Globals.ThisAddIn.Application.ActiveExplorer().SelectionChange += new Outlook.ExplorerEvents_10_SelectionChangeEventHandler(Globals.ThisAddIn.CurrentExplorer_SelectionChangeEvent); outlookNameSpace = Globals.ThisAddIn.Application.GetNamespace("MAPI"); inbox = outlookNameSpace.Stores[Globals.ThisAddIn.myCredentials.EmailID].GetDefaultFolder( Microsoft.Office.Interop.Outlook. OlDefaultFolders.olFolderInbox); items = inbox.Items; items.ItemAdd += new Microsoft.Office.Interop.Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd); string hasfsub = WebRequestHelper.getResponse(featuresURL); return(hasfsub); //Read Features Submitted Registry ,False //const string subkey = @"Software\MailTangy"; //using (var key = Registry.CurrentUser.OpenSubKey(subkey)) //{ // if (key != null) // { // return key.GetValue("HaveFeaturesSubmitted", false).ToString(); // } // else // return "False"; //} }
public static void AppointmentCancel(String subject) { Outlook.Application oApp = null; Outlook.NameSpace mapiNamespace = null; Outlook.MAPIFolder CalendarFolder = null; Outlook.Items outlookCalendarItems = null; oApp = new Outlook.Application(); mapiNamespace = oApp.GetNamespace("MAPI"); CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); outlookCalendarItems = CalendarFolder.Items; foreach (Outlook.AppointmentItem item in outlookCalendarItems) { Console.WriteLine("Current item: " + item.Subject); if (item.Subject == subject) { Console.WriteLine("Cancelling Appointment"); } { item.MeetingStatus = Outlook.OlMeetingStatus.olMeetingCanceled; item.ForceUpdateToAllAttendees = true; item.Save(); ((Outlook._AppointmentItem)item).Send(); ((Outlook._AppointmentItem)item).Close(Outlook.OlInspectorClose.olSave); item.Delete(); break; } } }
private void ConnectToOutlook() { // Checks whether an Outlook process is currently running try { if (Process.GetProcessesByName("OUTLOOK").Count() > 0) { Log.Out(Log.Severity.Info, "Connection", "Connecting to an existing Outlook instance"); try { _outlook = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application"); } catch (Exception ex) { throw ex; } _keepOutlookRunning = true; return; } // Creates a new instance of Outlook and logs on to the specified profile. Log.Out(Log.Severity.Info, "Connection", "Starting a new Outlook session"); _outlook = new Outlook.Application(); Outlook.NameSpace nameSpace = _outlook.GetNamespace("MAPI"); Outlook.Folder mailFolder = (Outlook.Folder)nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); } catch (Exception) { Log.Out(Log.Severity.Error, "Connection", "Error encountered when connecting to Outlook "); throw; } }
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; } }
internal static IEnumerable <Outlook.Store> GetStores(this Outlook.NameSpace item) { foreach (var store in item.Stores.OfType <Outlook.Store>()) { yield return(store); } }
private void btnFolderSelect_Click(object sender, EventArgs e) { object missing = Missing.Value; //get the Outlook Application Object Outlook.Application outlookApplication = new Outlook.Application(); //get the namespace object Outlook.NameSpace nameSpace = outlookApplication.GetNamespace("MAPI"); //Logon to Session, here we use an already opened Outlook session nameSpace.Logon(missing, missing, false, false); //get the InboxFolder Outlook.MAPIFolder Folder = nameSpace.PickFolder(); if (Folder != null) { txtMoveToFolder.Text = Folder.Name; this.Profile.MoveFolderName = Folder.EntryID; this.Profile.MoveFolderStoreId = Folder.StoreID; } //release used resources if (Folder != null) { Marshal.ReleaseComObject(Folder); } //logof from namespace nameSpace.Logoff(); //release resources Marshal.ReleaseComObject(nameSpace); Marshal.ReleaseComObject(outlookApplication.Application); }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { outlookNameSpace = this.Application.GetNamespace("MAPI"); inbox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); items = inbox.Items; items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd); }
public void TestFixtureSetUp() { _sender = new EmailSender(); _app = _sender.Initialise(); _outlookSession = _app.Session; _outlookSession.Logon("Outlook", "", false, true); }
public OLCalReader(String profileName) { myOutlook = new Outlook.Application (); myProfile = myOutlook.Session; this.profileName = profileName; Logon (); }
public static Outlook.Items GetCalendarItemsInTimeFrame( DateTime reportStart, DateTime reportEnd) { Outlook.NameSpace session = Globals.ThisAddIn.Application.Session; Outlook.Folder calendar = session.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder; // Specify the filter this way to include appointments that // overlap with the specified date range but do not necessarily // fall entirely within the date range. // Date values in filter must not include seconds. string filter = string.Format( "[Start] < '{0}' AND [End] > '{1}'", reportEnd.ToString("MM/dd/yyyy hh:mm tt"), reportStart.ToString("MM/dd/yyyy hh:mm tt")); // Include recurring calendar items. Outlook.Items calendarItems = calendar.Items; calendarItems.Sort("[Start]", Type.Missing); calendarItems.IncludeRecurrences = true; calendarItems = calendarItems.Restrict(filter); return(calendarItems); }
private void button7_Click(object sender, RibbonControlEventArgs e) { Outlook.NameSpace namespce = null; Outlook.Items tasks = null; Outlook.Application oApp = new Outlook.Application(); namespce = oApp.GetNamespace("MAPI"); tasks = namespce.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderTasks).Items; string temp = string.Empty; string tmpRedm = string.Empty; bool isExist = false; string AddedTastFromOutlook = string.Empty; foreach (Outlook.TaskItem task in tasks) { tmpRedm += task.Subject + Environment.NewLine; //temp += $"{task.Body}+{Environment.NewLine}"; //bool isCompleeted = task.Complete;//Check if your task is compleeted in your application you could use EntryID property to identify a task //if (isCompleeted == true && task.Status != OlTaskStatus.olTaskComplete) //{ // task.MarkComplete(); // task.Save(); //} } foreach (Issue issue in manager.GetObjectList <Issue>(new NameValueCollection())) { temp += issue.Subject + Environment.NewLine; } MessageBox.Show("TASK outlook" + Environment.NewLine + tmpRedm); MessageBox.Show("TASK Redmine" + Environment.NewLine + temp); }
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); }
/// <summary> /// 从OutLook中取出用户 /// </summary> /// <param name="fields"></param> /// <param name="ds"></param> /// <returns></returns> public static Boolean getMailAddressFromOUTLOOK(string[] fields, ref DataSet ds) { try { // Create the Outlook application. Outlook.Application oApp = new Outlook.Application(); //Get the MAPI namespace. Outlook.NameSpace oNS = oApp.Session; //Get the AddressLists collection. Outlook.AddressLists oALs = oNS.AddressLists; //Loop through the AddressLists collection. Outlook.AddressList oAL; for (int i = 1; i <= oALs.Count; i++) { oAL = (Outlook.AddressList)oALs.GetEnumerator().Current; // oALs.GetEnumerator().MoveNext(); } }//end of try block catch (System.Exception ex) { NCLogger.GetInstance().WriteExceptionLog(ex); return(false); //MessageBox.Show("outllok " + ex.Message); } //end of catch return(true); } //end of Email Method
private void linkEmail_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { Outlook.Application outlookApplication = new Outlook.Application(); Outlook.NameSpace nameSpace = outlookApplication.GetNamespace("MAPI"); Outlook.Folder folderInbox = (Outlook.Folder)nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); Outlook.MailItem mailItem = (Outlook.MailItem)outlookApplication.CreateItem(Outlook.OlItemType.olMailItem); mailItem.Subject = "Activation Request: " + trialMaker.ProductName + " for Revit 2013"; StringBuilder strBuilder = new StringBuilder(); strBuilder.AppendLine("I'm sending a request for the " + trialMaker.ProductName + " with the following information."); strBuilder.AppendLine(""); strBuilder.AppendLine("Company Name: " + trialMaker.CompanyName); strBuilder.AppendLine(""); strBuilder.AppendLine("**** All characters are case-sensitive. *****"); strBuilder.AppendLine("**** Our HOK team will contact you shortly. *****"); mailItem.Body = strBuilder.ToString(); mailItem.Display(false); } catch (Exception ex) { MessageBox.Show("Failed to request an activation code.\n" + ex.Message, "TrialMakerForm:linkEmail_LinkClicked", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// 获取 Outlook 地址簿列表. /// </summary> /// <returns></returns> public List <UserAddressBook> ReadAddressBookList() { List <UserAddressBook> resultList = new List <UserAddressBook>(); Outlook.NameSpace mynamespace = outlookApp.GetNamespace("MAPI"); Outlook.MAPIFolder myFolder = mynamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts); int iMailCount = myFolder.Items.Count; for (int k = 1; k <= iMailCount; k++) { Outlook.ContactItem item = (Outlook.ContactItem)myFolder.Items[k]; UserAddressBook result = new UserAddressBook(); // 姓名. result.UserName = item.LastName; // 邮件地址. result.Email = item.Email1Address; // 号码. result.Mobile = item.MobileTelephoneNumber; // 部门. result.Department = item.Department; // 加入列表. resultList.Add(result); } return(resultList); }
//how to construct for email public static bool SendMail(string MessageBody, string Username) { try { Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace NS = app.GetNamespace("MAPI"); Microsoft.Office.Interop.Outlook.MAPIFolder objFolder = NS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox); Microsoft.Office.Interop.Outlook.MailItem objMail = (Microsoft.Office.Interop.Outlook.MailItem)objFolder.Items.Add(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); //objMail.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText; objMail.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML; objMail.Body = MessageBody; objMail.Subject = "Your Recipe For Day " + DateTime.Now.Date.AddDays(1).ToString("dd/MM/yyyy"); string email = GetEmailFromDbs(Username, GetConnectionString()); objMail.To = email; objMail.CC = ""; objMail.Send(); return(true); } catch (System.Exception) { return(false); } }
private AbstractItem CreateAppointment(string outlookId, string crmId, Outlook.OlMeetingStatus status) { AbstractItem result; Outlook.NameSpace session = Globals.ThisAddIn.GetOutlookSession(); if (session != null) { Outlook.AppointmentItem legacy = null; Outlook.MAPIFolder folder = session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); if (!string.IsNullOrEmpty(outlookId)) { legacy = folder.Items.Add(Outlook.OlItemType.olAppointmentItem); legacy.MeetingStatus = status; result = new CallItem(legacy); result.CrmEntryId = crmId; this.ByCrmId[crmId] = result; this.ByOutlookId[legacy.EntryID] = result; } else { result = FindExistingAppointmentItem(outlookId, crmId, folder); } } else { throw new ShouldNotHappenException("No Outlook session!"); } return(result); }
public NameSpaceWrapper(object obj) { Utility.LogNameSpaceEvent(LogType.Diagnostic, (string.Format("{0}{1}", new StackTrace().GetFrame(0).GetMethod().Name, System.Environment.NewLine))); this._myObject = obj; _pConnectionPointContainer = _myObject as IConnectionPointContainer; if (_pConnectionPointContainer != null) { _pConnectionPoint = null; _pConnectionPointContainer.FindConnectionPoint(_sourceIntfGuid, out _pConnectionPoint); if (_pConnectionPoint != null) { _pConnectionPoint.Advise(this, out _cookie); nameSpace = _myObject as Outlook.NameSpace; inboxMAPIFolder = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); // inboxMAPIFolder is released within the wrapper outboxMAPIFolder = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox); // outboxMAPIFolder is released within the wrapper sentItemsMAPIFolder = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail); // sentItemsMAPIFolder is released within the wrapper if (ControlPanel.TrackInboxEnabled) { new FolderWrapper(inboxMAPIFolder); } if (ControlPanel.TrackOutboxEnabled) { new FolderWrapper(outboxMAPIFolder); } if (ControlPanel.TrackSentItemsEnabled) { new FolderWrapper(sentItemsMAPIFolder); } } } }
private static void GetConfig(Microsoft.Office.Interop.Outlook.NameSpace ns, String mode) { //Reference:https://github.com/n1nj4sec/pupy/blob/unstable/pupy/modules/outlook.py Console.WriteLine("[*] Try to get config"); Console.WriteLine(); Object CurrentProfileName = ns.GetType().InvokeMember("CurrentProfileName", System.Reflection.BindingFlags.GetProperty, null, ns, null); Console.WriteLine("[*] CurrentProfileName:" + CurrentProfileName.ToString()); Object ExchangeMailboxServerName = ns.GetType().InvokeMember("ExchangeMailboxServerName", System.Reflection.BindingFlags.GetProperty, null, ns, null); Console.WriteLine("[*] ExchangeMailboxServerName:" + ExchangeMailboxServerName.ToString()); Object ExchangeMailboxServerVersion = ns.GetType().InvokeMember("ExchangeMailboxServerVersion", System.Reflection.BindingFlags.GetProperty, null, ns, null); Console.WriteLine("[*] ExchangeMailboxServerVersion:" + ExchangeMailboxServerVersion.ToString()); if (mode == "all") { Console.WriteLine("[!] Notice:When the antivirus software is inactive or out-of-date,it will pop up a Outlook security prompt.\r\n"); Console.WriteLine("[*] Account-DisplayName:" + ns.Accounts[1].DisplayName); Console.WriteLine("[*] Account-SmtpAddress:" + ns.Accounts[1].SmtpAddress); Console.WriteLine("[*] Account-AutoDiscoverXml:\r\n" + ns.Accounts[1].AutoDiscoverXml); Console.WriteLine("[*] Account-AccountType:" + ns.Accounts[1].AccountType); } }
private Outlook.MAPIFolder GetCalendarFolder() { if (calendarName == sqlController.SettingRead(Settings.calendarName)) { return(calendarFolder); } else { calendarName = sqlController.SettingRead(Settings.calendarName); Outlook.Application oApp = new Outlook.Application(); Outlook.NameSpace mapiNamespace = oApp.GetNamespace("MAPI"); Outlook.MAPIFolder oDefault = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Parent; try { calendarFolder = GetCalendarFolderByName(oDefault.Folders, calendarName); if (calendarFolder == null) { throw new Exception(t.GetMethodName() + " failed, for calendarName:'" + calendarName + "'. No such calendar found"); } } catch (Exception ex) { throw new Exception(t.GetMethodName() + " failed, for calendarName:'" + calendarName + "'", ex); } return(calendarFolder); } }
// Although NewMailEx event is triggered before outlook rule processing, these 2 run asynchronized, // so the rule processing doesn't guarentee to run "after" the completion of NewMailEx handler. // And NewMailEx event will not be triggered for every new mail if a lot of new mails coming in a short period of time. // // so the most reliable way to process every new mail is to add an outlook email rule to "run a script" for // every new mail. // // put the following function into outlook vba editor, under "TheOutlookSession", and create an email rule // to "run a script" this one. // // Enable "run a script" in Outlook 2013: // Create a DWORD "EnableUnsafeClientMailRules" under // HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Outlook\Security, and set to 1 // // Public Sub XXX(Item As Outlook.MailItem) // Header = Item.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E") // Pos = InStr(Header, "X-Mailer: nodemailer") // If Pos Then // Item.Categories = "No need to popup new mail alarm" // Item.Save // End If // End Sub private void ApplicationNewMailEx(string EntryIDCollection) { Outlook.NameSpace nameSpace = Application.GetNamespace("MAPI"); string[] entryIds = EntryIDCollection.Split(','); for (int i = 0; i < entryIds.Length; ++i) { Outlook.MailItem mailItem = null; try { mailItem = nameSpace.GetItemFromID(entryIds[i]) as Outlook.MailItem; } catch (COMException) { } if (mailItem != null) { FilterEmailUtil.FilterOutUnwantedEmail(mailItem); if (Config.AutoBackupEmailFromMe == true && Util.GetSenderSMTPAddress(mailItem) == Config.MyEmailAddress) { BackupEmailUtil.MarkEmailReadAndClearAllCategories(mailItem); EmailFlagUtil.FlagEmail(mailItem); BackupEmailUtil.BackupEmail(mailItem); } } } }
private void ButtonSendPath_Click(object sender, EventArgs e) { Outlook.NameSpace outlookNameSpace = Globals.ThisAddIn.Application.GetNamespace("MAPI"); Outlook.MAPIFolder pickedFolder = outlookNameSpace.PickFolder(); string folderPath; if (pickedFolder.FolderPath is object) { folderPath = pickedFolder.FolderPath; if (folderPath.StartsWith(@"\\")) { folderPath = folderPath.Remove(0, 2); } Log.Message("FolderPath : " + folderPath); } else { folderPath = ""; } LabelSendPathValue.Text = folderPath; contact.SentPath = folderPath; if (pickedFolder is object) { Marshal.ReleaseComObject(pickedFolder); } if (outlookNameSpace is object) { Marshal.ReleaseComObject(outlookNameSpace); } }
private void Application_NewMailEx(string entryIdItem) { Outlook.NameSpace ns = Application.GetNamespace("MAPI"); var item = ns.GetItemFromID(entryIdItem); try { if (item is Outlook.MailItem) { var processor = new MailItemProcessor(item as Outlook.MailItem); var controller = new LogResultsTaskController(); processor.NewResultsAvailable += controller.OnNewResultsAvailable; controller.LogResultsTaskCompleted += SendSuccessMail; processor.ProcessMailRule(); return; } } catch (AggregateException ex) { var p = from innerEx in ex.InnerExceptions select innerEx.Message; string errorMessages = String.Join <string>("\n", p.ToList()); SendErrorMail(errorMessages); } catch (Exception ex) { SendErrorMail(ex.Message); } }
/* This method is called when the addin first starts * Functionality : This method initializes connection, updates the DB for the first time * and sets up all the Event Handlers. */ private void ThisAddIn_Startup(object sender, System.EventArgs e) { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); //Important DO NOT Delete //Startup and ItemLoad Event Handlers this.Application.Startup += ApplicationStartup; this.Application.ItemLoad += ApplicationItemLoad; Instance = this; //Check if table is populated bool isUpdated = CheckInitialStatus(); if (!isUpdated) { GetEmailFromInbox(); //Get EmailId from Inbox InsertAddress(); //Insert EmailId in DB NoteStatus(); //Update config table emailProtection = true; //If first run, enable email protection replytoProtection = true; //If first run, enable reply-to protection } outlookNameSpace = this.Application.GetNamespace("MAPI"); inbox = outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); items = inbox.Items; items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(itemsEmailReceived); //Event Handler for new incoming emails //Explorer Events Event Handler : Main Trigger currentExplorer = this.Application.ActiveExplorer(); currentExplorer.SelectionChange += new Outlook.ExplorerEvents_10_SelectionChangeEventHandler(CurrentExplorerEvent); }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { //Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.Machine); try { //System.Windows.Forms.MessageBox.Show(String.) AddACategory(); Set_clientnrList(); mappen = serial.Deserialize(mappen, @"D:\data\paths.txt"); mappen2 = Get_mappen(@"D:\Data"); outlookNameSpace = this.Application.GetNamespace("MAPI"); inbox = outlookNameSpace.GetDefaultFolder( Microsoft.Office.Interop.Outlook. OlDefaultFolders.olFolderInbox); items = inbox.Items; items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(New_Item_Handler); } catch (System.Exception error) { System.Windows.Forms.MessageBox.Show("error = " + error.Message); } }
private Appointment CreateAppointment(Appointment appointment) { try { Outlook.Application outlookApp = new Outlook.Application(); // creates new outlook app Outlook.AppointmentItem newAppo = (Outlook.AppointmentItem)outlookApp.CreateItem(Outlook.OlItemType.olAppointmentItem); // creates a new appointment newAppo.AllDayEvent = false; newAppo.ReminderSet = false; newAppo.Location = appointment.Location; newAppo.Start = appointment.Start; newAppo.Duration = appointment.Duration; newAppo.Subject = appointment.Subject; newAppo.Body = appointment.Body; newAppo.Save(); Appointment returnAppo = new Appointment(newAppo.GlobalAppointmentID, newAppo.Start, newAppo.Duration, newAppo.Subject, newAppo.Location, newAppo.Body, t.Bool(sqlController.SettingRead(Settings.colorsRule)), true, sqlController.Lookup); Outlook.MAPIFolder calendarFolderDestination = GetCalendarFolder(); Outlook.NameSpace mapiNamespace = outlookApp.GetNamespace("MAPI"); Outlook.MAPIFolder oDefault = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); if (calendarFolderDestination.Name != oDefault.Name) { newAppo.Move(calendarFolderDestination); } return(returnAppo); } catch (Exception ex) { throw new Exception("The following error occurred: " + ex.Message); } }
public void PrintEmailDetails() { oApp = new Outlook.Application(); // Get the MAPI namespace. Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); //Get the Inbox folder. Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Get the Items collection in the Inbox folder. Outlook.Items oItems = oInbox.Items; //Output some common properties. for (int i = oItems.Count; i > oItems.Count - 5; i--) { Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oItems[i]; Console.WriteLine("Subject: {0}", oMsg.Subject); Console.WriteLine("From: {0} <{1}>", oMsg.SenderName, oMsg.SenderEmailAddress); Console.WriteLine("To: {0}", oMsg.To); Console.WriteLine("ReceivedTime: {0}", oMsg.ReceivedTime); Console.WriteLine("Links: {0}", oMsg.Links); int AttachCnt = oMsg.Attachments.Count; Console.WriteLine("Attachments: " + AttachCnt.ToString()); if (AttachCnt > 0) { for (int j = 1; j <= AttachCnt; j++) { Console.WriteLine(j.ToString() + "-" + oMsg.Attachments[j].DisplayName); } } Console.WriteLine("Size: {0} KB", oMsg.Size / 1024); Console.WriteLine("---------------------------------"); } }
/// <summary> /// Release com object /// </summary> /// <param name="obj">Com object</param> private static void ReleaseObj(object obj) { try { if (obj is Outlook.Application) { Outlook.NameSpace nameSpace = (obj as Outlook.Application).GetNamespace("MAPI"); if (nameSpace != null) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(nameSpace); } (obj as Outlook._Application).Quit(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj); GC.Collect(); GC.WaitForPendingFinalizers(); } } catch (Exception e) { throw new Exception(e.Message); } finally { obj = null; } Thread.Sleep(waittime_item); }
public void Dispose() { helpers.addLog("Disposing..."); MailNS.Logoff(); MailNS = null; MyInbox = null; //InboxMailItem = null; ((Microsoft.Office.Interop.Outlook._Application)MyApp).Quit(); ////MyApp.Quit(); MyApp = null; helpers.addLog("Dispose done."); }
public void TestFixtureSetUp() { m_sender = new EmailSender(); m_app = m_sender.Initialise(); m_outlookSession = m_app.Session as Outlook.NameSpace; m_outlookSession.Logon("Outlook", "", false, true); #if DEBUG m_manifestPath = Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\Win32\debug\Workshare.RegFreeCom.manifest"); #else m_manifestPath = Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\Win32\release\Workshare.RegFreeCom.manifest"); #endif }
/// <summary> /// Initalizes and logs into an Outlook session. Must call this /// before using any of the other methods of this class. /// </summary> public void Initialize() { if (_isInitialized) { // Already initialized. Return silently. return; } _olNS = _olApp.GetNamespace("MAPI"); _olNS.Logon(Missing.Value, Missing.Value, Missing.Value, true); _olContactsFolder = _olNS.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderContacts); _isInitialized = true; }
protected virtual void Dispose(bool isDisposing) { if (isDisposing) { GC.SuppressFinalize(this); } if (_items != null) Marshal.ReleaseComObject(_items); if (_ns != null) Marshal.ReleaseComObject(_ns); if (_sent != null) Marshal.ReleaseComObject(_sent); _ns = null; _sent = null; _items = null; }
public OutlookClass() { try { //start outlook MyApp = new Application(); MailNS = MyApp.GetNamespace("MAPI"); string sProfile = "", sPassword=""; bool bShowDialog = true, bNewSession=false; MailNS.Logon(sProfile, sPassword, bShowDialog, bNewSession); MyInbox = MailNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox); } catch (System.Exception ex) { helpers.addLog("Exception: " + ex.Message); } }
/* private Queue queue_spam = null; private Queue queue_ham = null; private Thread thread_spam = null; private Thread thread_ham = null; */ public MailParser(Logger log, Outlook.Application objOutlook, Worker w) { this.logger = log; this.outlook = objOutlook; this.ns = this.outlook.GetNamespace("MAPI"); this.ns.Logon(Missing.Value, Missing.Value, false, false); this.wrapper = new MAPIPropWrapper(); this.wrapper.Initialize(); this.worker = w; /* this.queue_spam = new Queue(); this.queue_ham = new Queue(); this.thread_spam = new Thread(new ThreadStart(this.handleSpam)); // this.thread_spam.Start(); this.thread_ham = new Thread(new ThreadStart(this.handleHam)); // this.thread_ham.Start(); */ }
public void LoginToOutlook() { if (_outlookApp == null) { _outlookApp = new Outlook.Application(); _outlookNamespace = _outlookApp.GetNamespace("mapi"); } /// TODO: RedemptioN? _outlookNamespace.Logon(OutlookProfile, null, true, false); }
private static void CreateOutlookInstance() { if (OutlookApplication == null || _outlookNamespace == null) { //Try to create new Outlook application 3 times, because mostly it fails the first time, if not yet running for (int i = 0; i < 3; i++) { try { // First try to get the running application in case Outlook is already started try { OutlookApplication = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application; } catch (COMException) { // That failed - try to create a new application object, launching Outlook in the background OutlookApplication = new Outlook.Application(); } break; //Exit the for loop, if creating outllok application was successful } catch (COMException ex) { if (i == 2) throw new NotSupportedException("Could not create instance of 'Microsoft Outlook'. Make sure Outlook 2003 or above version is installed and retry.", ex); else //wait ten seconds and try again System.Threading.Thread.Sleep(1000 * 10); } } if (OutlookApplication == null) throw new NotSupportedException("Could not create instance of 'Microsoft Outlook'. Make sure Outlook 2003 or above version is installed and retry."); //Try to create new Outlook namespace 3 times, because mostly it fails the first time, if not yet running for (int i = 0; i < 3; i++) { try { _outlookNamespace = OutlookApplication.GetNamespace("MAPI"); break; //Exit the for loop, if creating outllok application was successful } catch (COMException ex) { if (i == 2) throw new NotSupportedException("Could not connect to 'Microsoft Outlook'. Make sure Outlook 2003 or above version is installed and running.", ex); else //wait ten seconds and try again System.Threading.Thread.Sleep(1000 * 10); } } if (_outlookNamespace == null) throw new NotSupportedException("Could not connect to 'Microsoft Outlook'. Make sure Outlook 2003 or above version is installed and retry."); else Logger.Log("Connected to Outlook: " + VersionInformation.GetOutlookVersion(OutlookApplication), EventType.Debug); } /* // Get default profile name from registry, as this is not always "Outlook" and would popup a dialog to choose profile // no matter if default profile is set or not. So try to read the default profile, fallback is still "Outlook" string profileName = "Outlook"; using (RegistryKey k = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\Outlook\SocialConnector", false)) { if (k != null) profileName = k.GetValue("PrimaryOscProfile", "Outlook").ToString(); } _outlookNamespace.Logon(profileName, null, true, false);*/ //Just try to access the outlookNamespace to check, if it is still accessible, throws COMException, if not reachable if (string.IsNullOrEmpty(SyncContactsFolder)) { _outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts); } else { _outlookNamespace.GetFolderFromID(SyncContactsFolder); } }
public void Dispose() { try { this.handleAutotrain(false); /* if ((this.thread_spam != null) && (this.thread_spam.IsAlive)) { this.thread_spam.Abort(); this.thread_spam = null; } if ((this.thread_ham != null) && (this.thread_ham.IsAlive)) { this.thread_ham.Abort(); this.thread_ham = null; } */ if (this.wrapper != null) { this.wrapper.Uninitialize(); this.wrapper = null; } if (this.ns != null) { this.ns.Logoff(); this.ns = null; } } catch (Exception ex) { this.logger.WriteError("MailParser.Dispose() " + ex.Message); this.logger.WriteError(ex.StackTrace); } }
/// <summary> /// Fetch amount of time spent in minutes for todays date /// </summary> /// <returns></returns> public static double GetMeetingDuration() { Outlook.NameSpace nameSpace; Outlook.Application outlookApplication; Outlook.Folder fldCalander; double meetingMinutes = 0; try { outlookApplication = new Outlook.Application(); nameSpace = outlookApplication.GetNamespace("mapi"); var profile = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles", "DefaultProfile", null); nameSpace.Logon(profile, Missing.Value, true, true); fldCalander = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder; Outlook.Items items = GetAppointmentsInRange(fldCalander); if (items != null) { foreach (Outlook.AppointmentItem oAppt in items) { meetingMinutes += (oAppt.End - oAppt.Start).TotalMinutes; } } } catch (Exception) { throw; } finally { fldCalander = null; nameSpace = null; } return meetingMinutes; }
/// <summary> /// code written by Joy /// excutes ansd the start the timer upload process when the backgoundworkers's do work event fires /// </summary> /// <param name="Item"></param> void doBackGroundUpload(object Item) { try { Globals.ThisAddIn.isTimerUploadRunning = true; OutlookObj = Globals.ThisAddIn.Application; outlookNameSpace = OutlookObj.GetNamespace("MAPI"); Outlook.MAPIFolder oInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); Outlook.MAPIFolder olMailRootFolder = (Outlook.MAPIFolder)oInBox.Parent; oMailRootFolders = olMailRootFolder.Folders; Outlook.MailItem moveMail = (Outlook.MailItem)Item; string newCatName = "Successfully Uploaded"; if (Globals.ThisAddIn.Application.Session.Categories[newCatName] == null) { outlookNameSpace.Categories.Add(newCatName, Outlook.OlCategoryColor.olCategoryColorDarkGreen, Outlook.OlCategoryShortcutKey.olCategoryShortcutKeyNone); } XmlNode uploadFolderNode = UserLogManagerUtility.GetSPSiteURLDetails("", folderName); if (uploadFolderNode != null) { bool isDroppedItemUplaoded = false; addinExplorer = ThisAddIn.OutlookObj.ActiveExplorer(); //Check the folder mapping with documnet library if (isUserDroppedItemsCanUpload == false) { //Show message try { Outlook.MailItem m = (Outlook.MailItem)Item; mailitemEntryID = m.EntryID; try { mailitem = m; mailitemEntryID = m.EntryID; string strsubject = m.EntryID; if (string.IsNullOrEmpty(strsubject)) { strsubject = "tempomailcopy"; } mailitemEntryID = strsubject; string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg"; if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false) { Directory.CreateDirectory(UserLogManagerUtility.RootDirectory); } m.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG); } catch (Exception ex) { } Outlook.MAPIFolder fp = (Outlook.MAPIFolder)m.Parent; DoNotMoveInNonDocLib(mailitemEntryID, fp); } catch (Exception) { NonDocMoveReportItem(Item); } MessageBox.Show("You are attempting to move files to a non document library. This action is not supported.", "ITOPIA", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (frmUploadItemsListObject == null || (frmUploadItemsListObject != null && frmUploadItemsListObject.IsDisposed == true)) { //frmUploadItemsListObject = new frmUploadItemsList(); // myCustomTaskPane = Globals.ThisAddIn.CustomTaskPanes.Add(frmUploadItemsListObject, "ITOPIA"); //myCustomTaskPane.Visible = true; IAddCustomTaskPane(); } //frmUploadItemsListObject.TopLevel = true; //frmUploadItemsListObject.TopMost = true; ////////////////////// frmUploadItemsListObject.Show(); try { ////// ////////// Outlook.MailItem oMailItem = (Outlook.MailItem)Item; parentfolder = (Outlook.MAPIFolder)oMailItem.Parent; try { mailitem = oMailItem; mailitemEntryID = oMailItem.EntryID; string strsubject = oMailItem.EntryID; if (string.IsNullOrEmpty(strsubject)) { strsubject = "tempomailcopy"; } mailitemEntryID = strsubject; string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg"; if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false) { Directory.CreateDirectory(UserLogManagerUtility.RootDirectory); } oMailItem.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG); } catch (Exception ex) { } string fileName = string.Empty; if (!string.IsNullOrEmpty(oMailItem.Subject)) { //Replce any specila characters in subject fileName = Regex.Replace(oMailItem.Subject, strMailSubjectReplcePattern, " "); fileName = fileName.Replace(".", "_"); } if (string.IsNullOrEmpty(fileName)) { DateTime dtReceivedDate = Convert.ToDateTime(oMailItem.ReceivedTime); fileName = "Untitled_" + dtReceivedDate.Day + "_" + dtReceivedDate.Month + "_" + dtReceivedDate.Year + "_" + dtReceivedDate.Hour + "_" + dtReceivedDate.Minute + "_" + dtReceivedDate.Millisecond; } UploadItemsData newUploadData = new UploadItemsData(); newUploadData.ElapsedTime = DateTime.Now; newUploadData.UploadFileName = fileName;// oMailItem.Subject; newUploadData.UploadFileExtension = ".msg"; newUploadData.UploadingMailItem = oMailItem; newUploadData.UploadType = TypeOfUploading.Mail; newUploadData.DisplayFolderName = folderName; frmUploadItemsListObject.UploadUsingDelegate(newUploadData); //Set dropped items is uploaded /////////////////////////updated by Joy on 25.07.2012///////////////////////////////// bool uploadStatus = frmUploadItemsListObject.IsSuccessfullyUploaded; XMLLogOptions userOption = UserLogManagerUtility.GetUserConfigurationOptions(); if (uploadStatus == true) { // Globals.ThisAddIn.isTimerUploaded = true; isDroppedItemUplaoded = true; for (int i = 0; i <= activeDroppingFolder.Items.Count; i++) { try { Outlook.MailItem me = (Outlook.MailItem)activeDroppingFolder.Items[i]; if (me.EntryID == mailitemEntryID) { me.Categories.Remove(0); me.Categories = newCatName; me.Save(); if (userOption.AutoDeleteEmails == true) { UserMailDeleteOption(mailitemEntryID, parentfolder); } } } catch (Exception ex) { } } frmUploadItemsListObject.lblPRStatus.Invoke(new updateProgresStatus(() => { frmUploadItemsListObject.lblPRStatus.Text = Globals.ThisAddIn.no_of_t_item_uploaded.ToString() + " " + "of" + " " + Globals.ThisAddIn.no_of_pending_items_to_be_uploaded.ToString() + " " + "Uploaded"; })); frmUploadItemsListObject.progressBar1.Invoke(new updateProgessBar(() => { frmUploadItemsListObject.progressBar1.Value = (((Globals.ThisAddIn.no_of_t_item_uploaded * 100 / Globals.ThisAddIn.no_of_pending_items_to_be_uploaded))); })); } else { isDroppedItemUplaoded = false; } /////////////////////////updated by Joy on 25.07.2012///////////////////////////////// } catch (Exception ex) { isDroppedItemUplaoded = MoveItemIsReportItem(Item); } try { if (isDroppedItemUplaoded == false) { //string tempName = oDocItem.Subject; string tempName = string.Empty; Outlook.DocumentItem oDocItem = (Outlook.DocumentItem)Item; try { Outlook._MailItem myMailItem = (Outlook.MailItem)addinExplorer.Selection[1]; foreach (Outlook.Attachment oAttachment in myMailItem.Attachments) { if (oAttachment.FileName == oDocItem.Subject) { tempName = oAttachment.FileName; tempName = tempName.Substring(tempName.LastIndexOf(".")); oAttachment.SaveAsFile(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName); //Read file data to bytes //byte[] fileBytes = File.ReadAllBytes(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName); System.IO.FileStream Strm = new System.IO.FileStream(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm); byte[] fileBytes = reader.ReadBytes(Convert.ToInt32(Strm.Length)); reader.Close(); Strm.Close(); //Replace any special characters are there in file name string fileName = Regex.Replace(oAttachment.FileName, strAttachmentReplacePattern, " "); //Add uplaod attachment item data to from list. UploadItemsData newUploadData = new UploadItemsData(); newUploadData.UploadType = TypeOfUploading.Attachment; newUploadData.AttachmentData = fileBytes; newUploadData.DisplayFolderName = activeDroppingFolder.Name; if (fileName.Contains(".")) { newUploadData.UploadFileName = fileName.Substring(0, fileName.LastIndexOf(".")); newUploadData.UploadFileExtension = fileName.Substring(fileName.LastIndexOf(".")); if (string.IsNullOrEmpty(newUploadData.UploadFileName.Trim())) { //check file name conatins empty add the date time newUploadData.UploadFileName = "Untitled_" + DateTime.Now.ToFileTime(); } } //Add to form frmUploadItemsListObject.UploadUsingDelegate(newUploadData); //Set dropped mail attachment items is uploaded. isDroppedItemUplaoded = true; newUploadData = null; //oDocItem.Delete(); break; } } } catch (InvalidCastException ex) { //Set dropped mail attachment items is uploaded to false isDroppedItemUplaoded = false; } if (isDroppedItemUplaoded == false) { tempName = oDocItem.Subject; tempName = tempName.Substring(tempName.LastIndexOf(".")); oDocItem.SaveAs(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, Type.Missing); System.IO.FileStream Strm = new System.IO.FileStream(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm); byte[] fileBytes = reader.ReadBytes(Convert.ToInt32(Strm.Length)); reader.Close(); Strm.Close(); //Replace any special characters are there in file name string fileName = Regex.Replace(oDocItem.Subject, strAttachmentReplacePattern, " "); //Add uplaod attachment item data to from list. UploadItemsData newUploadData = new UploadItemsData(); newUploadData.UploadType = TypeOfUploading.Attachment; newUploadData.AttachmentData = fileBytes; newUploadData.DisplayFolderName = activeDroppingFolder.Name; if (fileName.Contains(".")) { newUploadData.UploadFileName = fileName.Substring(0, fileName.LastIndexOf(".")); newUploadData.UploadFileExtension = fileName.Substring(fileName.LastIndexOf(".")); if (string.IsNullOrEmpty(newUploadData.UploadFileName.Trim())) { //check file name conatins empty add the date time newUploadData.UploadFileName = "Untitled_" + DateTime.Now.ToFileTime(); } } //Add to form frmUploadItemsListObject.UploadUsingDelegate(newUploadData); newUploadData = null; //oDocItem.Delete(); } } } catch (Exception ex) { //throw ex; //////////////////////////////updated by Joy on 28.07.2012/////////////////////////////////// // EncodingAndDecoding.ShowMessageBox("FolderItem Add Event_DocItem Conv", ex.Message, MessageBoxIcon.Error); //////////////////////////////updated by Joy on 28.07.2012/////////////////////////////////// } try { XMLLogOptions userOptions = UserLogManagerUtility.GetUserConfigurationOptions(); for (int i = 0; i <= parentfolder.Items.Count; i++) { try { Outlook.MailItem me = (Outlook.MailItem)parentfolder.Items[i]; if (me.EntryID == mailitemEntryID) { ///////////////////////////modified by Joy on 10.08.2012//////////////////////////////////// if (isDroppedItemUplaoded == true) { me.Categories.Remove(0); me.Categories = newCatName; me.Save(); if (userOptions.AutoDeleteEmails == true) { UserMailDeleteOption(mailitemEntryID, parentfolder); } //parentfolder.Items.Remove(i); } ///////////////////////////modified by Joy on 10.08.2012//////////////////////////////////// } } catch (Exception) { } } } catch (Exception) { } if (!string.IsNullOrEmpty(mailitemEntryID)) { if (ItemType == TypeOfMailItem.ReportItem) { UserReportItemDeleteOption(mailitemEntryID, parentfolder); } else { ///////////////////////////Updated by Joy on 16.08.2012....to be updated later/////////////////////////////// // UserMailDeleteOption(mailitemEntryID, parentfolder); ///////////////////////////Updated by Joy on 16.08.2012....to be updated later/////////////////////////////// } } } } catch (Exception ex) { EncodingAndDecoding.ShowMessageBox("Folder Item Add Event", ex.Message, MessageBoxIcon.Error); } //AddToUploadList(Item); }
public void LogoffOutlook() { try { Logger.Log("Disconnecting from Outlook...", EventType.Debug); if (_outlookNamespace != null) { _outlookNamespace.Logoff(); } } catch (Exception) { // if outlook was closed inbetween, we get an System.InvalidCastException or similar exception, that indicates that outlook cannot be acced anymore // so as outlook is closed anyways, we just ignore the exception here } finally { if (_outlookNamespace != null) Marshal.ReleaseComObject(_outlookNamespace); if (OutlookApplication != null) { Marshal.ReleaseComObject(OutlookApplication); GC.Collect(); GC.WaitForPendingFinalizers(); } _outlookNamespace = null; OutlookApplication = null; Logger.Log("Disconnected from Outlook", EventType.Debug); } }
/// <summary> /// code written by Joy /// moves or copies mail items to the selected mapped folder /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOk_Click(object sender, EventArgs e) { if (this.ValidateChildren() == true) { if (ThisAddIn.IsUploadingFormIsOpen == true) { if (Globals.ThisAddIn.frmlistObject != null) { Globals.ThisAddIn.frmlistObject.progressBar1.Value = Globals.ThisAddIn.frmlistObject.progressBar1.Minimum; Globals.ThisAddIn.frmlistObject.lblPRStatus.Text = ""; } } string selected_mapiFolderName = cmbOptions.Text; this.Close(); if (Globals.ThisAddIn.copy_button_clicked == true) { OutlookObj = Globals.ThisAddIn.Application; outlookNameSpace = OutlookObj.GetNamespace("MAPI"); olInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); parentFolder = (Microsoft.Office.Interop.Outlook.MAPIFolder)olInBox.Parent; string mappedFolderName = cmbOptions.SelectedItem.ToString(); mappedFolder = MAPIFolderWrapper.GetFolder(parentFolder, mappedFolderName); Outlook.MailItem mItem; Outlook.MailItem copyMail; Globals.ThisAddIn.isCopyRunninng = true; foreach (Object obj in Globals.ThisAddIn.copySelected) { if (obj is Outlook.MailItem) { mItem = (Outlook.MailItem)obj; copyMail = mItem.Copy() as Outlook.MailItem; copyMail.Move(mappedFolder); //doBackGroundUpload(mItem); } } } else if (Globals.ThisAddIn.move_button_clicked == true) { OutlookObj = Globals.ThisAddIn.Application; outlookNameSpace = OutlookObj.GetNamespace("MAPI"); olInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); parentFolder = (Microsoft.Office.Interop.Outlook.MAPIFolder)olInBox.Parent; string mappedFolderName = cmbOptions.SelectedItem.ToString(); mappedFolder = MAPIFolderWrapper.GetFolder(parentFolder, mappedFolderName); Outlook.MailItem mItem; Globals.ThisAddIn.isMoveRunning = true; foreach (Object obj in Globals.ThisAddIn.moveSelected) { if (obj is Outlook.MailItem) { mItem = (Outlook.MailItem)obj; mItem.Move(mappedFolder); //doBackGroundUpload(mItem); } } } } else return; }
/// <summary> /// <c>ReConnection</c> member function /// this function recreates the deleted folder in outlook /// </summary> /// <param name="xLogProperties"></param> /// <param name="parentfolder"></param> /// <returns></returns> public bool ReConnection(XMLLogProperties xLogProperties, Outlook.MAPIFolder parentfolder) { bool result = false; try { Outlook.MAPIFolder newFolder = null; ////////////////////////updated by Joy on 25.07.2012///////////////// Outlook.MAPIFolder newBrokenUploadsFolder = null; ////////////////////////updated by Joy on 25.07.2012///////////////// //outlookObj = new Outlook.Application(); OutlookObj = Globals.ThisAddIn.Application; //Gte MAPI Name space outlookNameSpace = OutlookObj.GetNamespace("MAPI"); Outlook.MAPIFolder olInboxFolder = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); Outlook.MAPIFolder Target = parentfolder; bool created = CreateFolderInOutLookSideMenu(xLogProperties.DisplayFolderName, xLogProperties.SiteURL, out newFolder, Target); if (created == true && newFolder != null) { //Set new folder location xLogProperties.OutlookFolderLocation = newFolder.FolderPath; //Create node in xml file // UserLogManagerUtility.CreateXMLFileForStoringUserCredentials(xLogProperties); MAPIFolderWrapper omapi = null; if (string.IsNullOrEmpty(xLogProperties.DocumentLibraryName) == true) { //Doc name is empty means Folder is not mapped with Doc Lib omapi = new MAPIFolderWrapper(ref newFolder, addinExplorer, false); } else { omapi = new MAPIFolderWrapper(ref newFolder, addinExplorer, true); } newFolders.Add(omapi); } } catch (Exception ex) { } return result; }
/// <summary> ///<c>ThisAddIn_Startup</c> Outlook startup event /// This Event is executed when outlook starts(outlook is opened) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ThisAddIn_Startup(object sender, System.EventArgs e) { try { //declare and initialize variables used for the Instant PLUS check Int32 result = 0; string filePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\ITOPIA\\SharePoint Link 2010\\", "SharePoint Link.xml"); //Make the call to Instant PLUS and store the result result = Ip2LibManaged.CallInstantPLUS(Ip2LibManaged.FLAGS_NONE, "30820274020100300D06092A864886F70D01010105000482025E3082025A02010002818100BA81817A32C249909671428137ECFC2AEF45E5F746C218550C2191F525A15E65DCD87CAD8B46EB870E55897D1D185B9D88BCDDB6D44CB8B9DDFD7DB4948E8CF91743377F31DB733438828CA0EC3176D8650C8F4B77578E60285F55049D9A707C61FF75C7C626492415BBCBE8058E4F220826A356F1C50B29C92B354C61BEF21F0201110281800AF88F254E47A9F97242E5CB5DA4874DD1D6EF68E60B6AD7D389810E6BA0149C94853482ADD6FECBB58C8F9DF2A71472ADB0C1BF75E665381C1DF855EA9EF93BBA5432731B506EDFE944C217EB09F27AA8203C7D7310D78995A9549690836B313CDCD0B2FA6AD79576977EB44B33D46577E9EA6939DCF8388761E25C3FADF9B1024100F3F70346EEA01874427576DFF5136A9B3A1AB4522ADD2073669376540C6CE65A1A613D0F4754FAD4C8DA70D3F5F5F0D4DAF97B0CF49D9BDA0ECE0F8F46A19BBF024100C3B4DA9372E3FDE1787C322A5B74F21800CDD6A4A85C1DC9D18D40B0F8736BDD3CF45CD5DDB8FD626CD1F11B1127439036A4974D257AF38EBCDD1D9CE08FC1A1024100AC35E43211DA6B9D5C16AE43BC0DB4A9CEA9703A00239E6F93B36295AE6AFCF44EDB3A28E70ECF2CCA039AEFF8E9D72CD6CE38BDD9D8AA3F91FADDCE8C35D75902405095C369E40386A8228D7E1170F3EB370F63D0DA63713971382B1AA3392077B57373ADC1796A4A3796385438525B762C52BC3E4CF150BEA42FA6577CD4EFE65102405162E2024CE04279E92731B490BE2431758FA6D032B0DB85B2AC782956832095800B4A8AB7D6FC1DB905CA38508FC3CC49994A48940CF9BB5761C07A9289D492", filePath); if (11574 != result) { //this.Close(); //this.Application.ActiveExplorer().Close(); //this.Application.Quit(); return; } isAuthorized = true; #region Add-in Express Regions generated code - do not modify this.FormsManager = AddinExpress.OL.ADXOlFormsManager.CurrentInstance; this.FormsManager.OnInitialize += new AddinExpress.OL.ADXOlFormsManager.OnComponentInitialize_EventHandler(this.FormsManager_OnInitialize); //this.FormsManager.ADXBeforeFolderSwitchEx += // new AddinExpress.OL.ADXOlFormsManager.BeforeFolderSwitchEx_EventHandler(FormsManager_ADXBeforeFolderSwitchEx); this.FormsManager.Initialize(this); #endregion //DateTime dtExpiredDate = new DateTime(2010, 08, 05); //DateTime dtWorkingDate = DateTime.Now; //TimeSpan t = new TimeSpan(); //t = dtExpiredDate.Subtract(dtWorkingDate); //if (t.Days < 30 && t.Days >= 0) //{ //outlookObj = new Outlook.Application(); OutlookObj = Globals.ThisAddIn.Application; //Gte MAPI Name space outlookNameSpace = OutlookObj.GetNamespace("MAPI"); //Get inbox folder Outlook.MAPIFolder oInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Get current user details to save the xml file based on user string userName = outlookNameSpace.DefaultStore.DisplayName; userName = userName.Replace("-", "_"); userName = userName.Replace(" ", ""); UserLogManagerUtility.UserXMLFileName = userName; //Get parent root folder Outlook.MAPIFolder olMailRootFolder = (Outlook.MAPIFolder)oInBox.Parent; //Get all folder oMailRootFolders = olMailRootFolder.Folders; //Create folder remove event oMailRootFolders.FolderRemove += new Microsoft.Office.Interop.Outlook.FoldersEvents_FolderRemoveEventHandler(oMailRootFolders_FolderRemove); //Set inbox folder as default try { OutlookObj.ActiveExplorer().CurrentFolder = oInBox; addinExplorer = this.Application.ActiveExplorer(); addinExplorer.BeforeItemPaste += new Microsoft.Office.Interop.Outlook.ExplorerEvents_10_BeforeItemPasteEventHandler(addinExplorer_BeforeItemPaste); //Create folder Switch event addinExplorer.FolderSwitch += new Microsoft.Office.Interop.Outlook.ExplorerEvents_10_FolderSwitchEventHandler(addinExplorer_FolderSwitch); //crete folder context menu disply this.Application.FolderContextMenuDisplay += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_FolderContextMenuDisplayEventHandler(Application_FolderContextMenuDisplay); this.Application.ContextMenuClose += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ContextMenuCloseEventHandler(Application_ContextMenuClose); strParentMenuTag = strParentMenuName; // Removing the Existing Menu Bar // RemoveItopiaMenuBarIfExists(strParentMenuTag); // Adding The Menu Bar Freshly // CreateParentMenu(strParentMenuTag, strParentMenuName); myTargetFolder = oInBox; CreateAddEventOnFolders(); //CreateDefaultAddEventOnFolders(); //Create outlook explorer wrapper class OutlookWindow = new OutlookExplorerWrapper(OutlookObj.ActiveExplorer()); OutlookWindow.Close += new EventHandler(OutlookWindow_Close); ((Outlook.ExplorerEvents_Event)addinExplorer).BeforeFolderSwitch += new Microsoft.Office.Interop.Outlook.ExplorerEvents_BeforeFolderSwitchEventHandler(ThisAddIn_BeforeFolderSwitch); oMailRootFolders.FolderChange += new Outlook.FoldersEvents_FolderChangeEventHandler(oMailRootFolders_FolderChange); foreach (Outlook.MAPIFolder item in oMailRootFolders) { try { item.Folders.FolderChange -= new Outlook.FoldersEvents_FolderChangeEventHandler(oMailRootFolders_FolderChange); } catch (Exception) { } item.Folders.FolderChange += new Outlook.FoldersEvents_FolderChangeEventHandler(oMailRootFolders_FolderChange); } Outlook.Items activeDroppingFolderItems; activeDroppingFolderItems = oInBox.Items; userOptions = UserLogManagerUtility.GetUserConfigurationOptions(); currentFolderSelected = oInBox.Name; currentFolderSelectedGuid = oInBox.EntryID; } catch (Exception ex) { ListWebClass.Log(ex.Message, true); } // } } catch (Exception ex) { EncodingAndDecoding.ShowMessageBox("StartUP", ex.Message, MessageBoxIcon.Error); } /// <summary> //code written by Joy ///initializes the object of timer /// </summary> System.Threading.AutoResetEvent reset = new System.Threading.AutoResetEvent(true); timer = new System.Threading.Timer(new System.Threading.TimerCallback(doBackgroundUploading), reset, 180000, 180000); GC.KeepAlive(timer); form = new Form(); form.Opacity = 0.01; form.Show(); form.Visible = false; }
public void start() { try { //start outlook MyApp = new Outlook.Application(); MailNS = MyApp.GetNamespace("MAPI"); } catch (System.Exception ex) { helpers.addLog("Exception: " + ex.Message); } }
public void Uninitialize() { if (_isInitialized) { try { _olNS.Logoff(); } catch { } _olContactsFolder = null; _olNS = null; _olApp = null; } }
private void ThisAddIn_Startup(object sender, EventArgs e) { //Executive flag addin _outlookNameSpace = Application.GetNamespace("MAPI"); _inbox = _outlookNameSpace.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderInbox); //Generate contacts from email I have received from capSpire _contacts = _outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts); _items = _inbox.Items; _items.ItemAdd += items_ItemAdd; AddContactsToItems(); _selectExplorers = Application.Explorers; _selectExplorers.NewExplorer += newExplorer_Event; AddToolbar(); }
public void LoginToOutlook() { Logger.Log("Connecting to Outlook...", EventType.Information); try { CreateOutlookInstance(); } catch (Exception e) { if (!(e is COMException) && !(e is System.InvalidCastException)) throw; try { // If outlook was closed/terminated inbetween, we will receive an Exception // System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) // so recreate outlook instance //And sometimes we we receive an Exception // System.InvalidCastException 0x8001010E (RPC_E_WRONG_THREAD)) Logger.Log("Cannot connect to Outlook, creating new instance....", EventType.Information); /*OutlookApplication = new Outlook.Application(); _outlookNamespace = OutlookApplication.GetNamespace("mapi"); _outlookNamespace.Logon();*/ OutlookApplication = null; _outlookNamespace = null; CreateOutlookInstance(); } catch (Exception ex) { string message = "Cannot connect to Outlook.\r\nPlease restart " + Application.ProductName + " and try again. If error persists, please inform developers on OutlookForge."; // Error again? We need full stacktrace, display it! throw new Exception(message, ex); } } }
/// <summary> /// Initializes the OutLook application and retrieves the meetings scheduled for current day. /// For logging into OutLook, we need the profile name. Default profile name is extracted from registry settings. /// </summary> private void InitializeMeetingDuration() { try { if (!Process.GetProcessesByName("OUTLOOK").Any()) return; outlookApplication = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application; nameSpace = outlookApplication.GetNamespace("mapi"); var profile = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles", "DefaultProfile", null); nameSpace.Logon(profile.ToString(), Missing.Value, true, true); fldCalander = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder; fldDeletedItems = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDeletedItems) as Outlook.Folder; items = GetAppointmentsInRange(fldCalander); fldCalander.BeforeItemMove += fldCalander_BeforeItemMove; items.ItemAdd += Items_ItemAdd; items.ItemChange += Items_ItemChange; if (items != null) { foreach (Outlook.AppointmentItem oAppt in items) { meetings.Add(oAppt.GlobalAppointmentID, new MeetingDetails(oAppt.Start, oAppt.End, oAppt.Duration)); } } } catch (Exception ex) { log.Error(ex.ToString()); } }
/// <summary> /// ctor /// </summary> /// <exception cref="System.Runtime.InteropServices.COMException"/> public OutlookManager() { var current = System.Security.Principal.WindowsIdentity.GetCurrent(); m_impContext = current.Impersonate(); System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("OUTLOOK"); int collCount = processes.Length; if (collCount != 0) { #region comment //try //{ // // create an application instance of Outlook // oApp = new Microsoft.Office.Interop.Outlook.Application(); //} //catch (System.Exception ex) //{ // try // { // // get Outlook in another way // oApp = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application; // } // catch (System.Exception ex2) // { // // try some other way to get the object // oApp = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application")) as Microsoft.Office.Interop.Outlook.Application; // } //} #endregion try { // Outlook already running, hook into the Outlook instance m_outlookApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application; } catch (System.Runtime.InteropServices.COMException ex) { if (ex.ErrorCode == -2147221021) m_outlookApp = new Application(); else throw; } } else m_outlookApp = new Microsoft.Office.Interop.Outlook.Application(); m_outNameSpace = m_outlookApp.GetNamespace("MAPI"); m_allFolders = m_outNameSpace.Folders; m_outlookApp.NewMailEx += new ApplicationEvents_11_NewMailExEventHandler(outLookApp_NewMailEx); this.FoldersInOutlook = new List<string>(); m_inboxFolder = m_outNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); m_FoldersToMonitor = new List<string>(); m_foldToMonitorInstances = new Dictionary<string, MAPIFolder>(StringComparer.OrdinalIgnoreCase); MAPIFolder mUserFolder = m_inboxFolder.Parent; if (mUserFolder != null) { foreach (object folder in mUserFolder.Folders) { MAPIFolder mapiFolder = folder as MAPIFolder; if (mapiFolder != null) { this.FoldersInOutlook.Add(mapiFolder.Name); } } } }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { RemoveMenubar(); AddMenuBar(); outlookNamespace = this.Application.GetNamespace("MAPI"); inbox = outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); outlookItems = inbox.Items; outlookItems.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd); }
public OutlookEmailWrapper(Outlook.NameSpace outlookSession) { m_outlookSession = outlookSession; Create(); }
public OutlookEmailWrapper(Outlook.NameSpace outlookSession, string msgFilename) { m_outlookSession = outlookSession; CreateFromTemplate(msgFilename); }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { _Explorers = this.Application.Explorers; _Inspectors = this.Application.Inspectors; _Namespace = this.Application.GetNamespace("MAPI"); _Explorers.Application.NewMailEx += new Outlook.ApplicationEvents_11_NewMailExEventHandler(Application_NewMailEx); }
private bool checkApps(bool excel) { GC.Collect(); GC.WaitForPendingFinalizers(); if (excel) { if (exApp != null) { Marshal.FinalReleaseComObject(exApp); } try { exApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); } catch (COMException ex) { Logger.log(TraceEventType.Error, 9, "Excel exception\r\n" + ex.GetType() + ":" + ex.Message + "\r\n" + ex.StackTrace); statusLabel.Content = "Excel couldn't be accessed. Excel not open?"; return false; } if (exApp == null) { statusLabel.Content = "Excel couldn't be accessed. Excel not open?"; return false; } } if (outApp != null) { Marshal.FinalReleaseComObject(outApp); } if (outNS != null) { Marshal.FinalReleaseComObject(outNS); } try { outApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application"); } catch (COMException ex) { Logger.log(TraceEventType.Error, 9, "Outlook exception\r\n" + ex.GetType() + ":" + ex.Message + "\r\n" + ex.StackTrace); statusLabel.Content = "Outlook couldn't be accessed. Outlook not open?+"; return false; } if (outApp == null) { statusLabel.Content = "Outlook couldn't be accessed. Outlook not open?"; } outNS = outApp.GetNamespace("MAPI"); if (outNS == null) { statusLabel.Content = "Uh oh... Bad things happened."; return false; } return true; }
//Method that runs when the plugin loads private void ThisAddIn_Startup(object sender, System.EventArgs e) { //Prompt to run application, and start and end timer System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show("Do you want to run SigX?", "Hit yes, I'll be quick", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { timer = Stopwatch.StartNew(); ReadMail(); //Start stopwatch and run batch parsing function } //Configure plugin to run when email is added to Inbox outlookNameSpace = this.Application.GetNamespace("MAPI"); inbox = outlookNameSpace.GetDefaultFolder( Microsoft.Office.Interop.Outlook. OlDefaultFolders.olFolderInbox); items = inbox.Items; items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(ReadSingleMail); // Modified method to run for single email }
public OutlookDataSource(IHostApplicationProvider hostAppProvider, IMail mailItem) { _mailItem = mailItem; Logger.LogInfo("OutlookSentItemSource.OutlookDataSource()"); _ns = hostAppProvider.Host.GetNamespace("MAPI"); _sent = _ns.GetDefaultFolder(MsOutlook.OlDefaultFolders.olFolderSentMail); _items = _sent.Items; }