public bool IniciarSesion(string cuenta, string contrasena) { bool resultado = true; _cuenta = cuenta; try { //Return a reference to the MAPI layer oApp = new Microsoft.Office.Interop.Outlook.Application(); oNameSpace = oApp.GetNamespace("MAPI"); /*********************************************************************** * Logs on the user * Profile: Set to null if using the currently logged on user, or set * to an empty string ("") if you wish to use the default Outlook Profile. * Password: Set to null if using the currently logged on user, or set * to an empty string ("") if you wish to use the default Outlook Profile * password. * ShowDialog: Set to True to display the Outlook Profile dialog box. * NewSession: Set to True to start a new session. Set to False to * use the current session. ***********************************************************************/ oNameSpace.Logon(_cuenta, contrasena, false, true); //gets defaultfolder for my Outlook Outbox oOutboxFolder = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox); } catch (Exception) { resultado = false; } return(resultado); }
// Uses recursion to enumerate Outlook subfolders. private void EnumerateFolders(Microsoft.Office.Interop.Outlook.MAPIFolder folder) { //cmbOutlookFolders.Items.Add(folder.Name); Microsoft.Office.Interop.Outlook.Folders childFolders = folder.Folders; if (childFolders.Count > 0) { foreach (Microsoft.Office.Interop.Outlook.MAPIFolder childFolder in childFolders) { try { // Write the folder path. Debug.WriteLine(childFolder.FolderPath); KeyValuePair <string, string> folderItem = new KeyValuePair <string, string>(childFolder.EntryID, childFolder.Name);// { } cmbOutlookFolders.Items.Add(folderItem); // Call EnumerateFolders using childFolder. EnumerateFolders(childFolder); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } }
private static Appointment LookForNextAppointment(string textToSearch) { Microsoft.Office.Interop.Outlook.Application oApp = null; Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null; Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null; Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null; oApp = new Microsoft.Office.Interop.Outlook.Application(); mapiNamespace = oApp.GetNamespace("MAPI"); ; CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); outlookCalendarItems = CalendarFolder.Items; outlookCalendarItems.Sort("[Start]"); var now = DateTime.Now.Date.ToString("g"); var nowIn1Year = DateTime.Now.Date.AddYears(1).ToString("g"); outlookCalendarItems = outlookCalendarItems.Restrict($"[Start] >= \"{now}\" AND [End] < \"{nowIn1Year}\" "); foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems) { var subject = item.Subject; if (subject.IndexOf(textToSearch,StringComparison.InvariantCultureIgnoreCase)!=-1) { return new Appointment() { Subject = subject, Start = item.Start }; } } return null; }
private static readonly object _lock = new object(); // Sync the processing of items in the Outbox public OutboxMonitor(Microsoft.Office.Interop.Outlook.Application application) { try { _application = application; _ns = _application.GetNamespace("MAPI"); _outbox = _ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox); _items = _outbox.Items; _items.ItemAdd += Items_ItemAdd; SubmitNonDeferredItems(); SyncroniseDeferredSendStore(); CreateSubmitWorkerThreads(); Logger.LogInfo("Secure File Transfer Outbox monitor created and configured."); } catch (Exception ex) { Dispose(); Logger.LogError(ex); Logger.LogError("Failed to create OutboxMonitor. Disable DeferredSend"); throw; } }
public static void CheckMailToExecute() { try { Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.ApplicationClass(); Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI"); Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); Microsoft.Office.Interop.Outlook.Items oItems = myInbox.Items.Restrict("[UnRead] = True"); foreach (var item in oItems) { if (item is Microsoft.Office.Interop.Outlook.MailItem) { Microsoft.Office.Interop.Outlook.MailItem mail = (Microsoft.Office.Interop.Outlook.MailItem)item; if (mail.UnRead && mail.Subject.StartsWith("MC")) { mail.UnRead = false; ExecuteMail(mail); } } } } catch (Exception ex) { Logger.Log(ex.Message); } }
/** * * Event handler when the Phish Email Folder button is clicked. * */ private void button1_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.MAPIFolder folder = null; // Have the user select the folder here... folder = olApp.Session.PickFolder(); // NOTE: The PickFolder() method will return a NULL folder IF AND // ONLY IF the user CANCELs the PickFolder dialogue!!! if (folder != null) { log.Debug( "Outlook Folder Selected: " + folder.Name + "; Full Path: " + folder.FullFolderPath); // Now set the Phishing Email Folder property... this.textBox3.Text = folder.Name; // Refresh the Form to show the change... this.Load += new System.EventHandler(this.PhishingOutlookAddInSettingsForm_Load); this.ResumeLayout(false); this.PerformLayout(); } }
static void ReadMail() { Microsoft.Office.Interop.Outlook.Application app = null; Microsoft.Office.Interop.Outlook._NameSpace ns = null; //Microsoft.Office.Interop.Outlook.MailItem item = null; Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null; app = new Microsoft.Office.Interop.Outlook.Application(); ns = app.GetNamespace("MAPI"); //ns.Logon(null, null, false, false); inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); // subFolder = inboxFolder.Folders["Inbox"]; //folder.Folders[1]; also works Console.WriteLine("Folder Name: {0}, EntryId: {1}", inboxFolder.Name, inboxFolder.EntryID); Console.WriteLine("Num Items: {0}", inboxFolder.Items.Count.ToString()); //System.IO.StreamWriter strm = new System.IO.StreamWriter("C:/Test/Inbox.txt"); for (int counter = 1; counter <= inboxFolder.Items.Count; counter++) { Console.Write(inboxFolder.Items.Count + " " + counter); dynamic item = inboxFolder.Items[counter]; //item = (Microsoft.Office.Interop.Outlook.MailItem)inboxFolder.Items[counter]; Console.WriteLine("Item: {0}", counter.ToString()); Console.WriteLine("Subject: {0}", item.Subject); Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString()); Console.WriteLine("Sendername: {0}", item.SenderName); Console.WriteLine("Body: {0}", item.Body); //strm.WriteLine(counter.ToString() + "," + item.Subject + "," + item.SentOn.ToShortDateString() + "," + item.SenderName); } //strm.Close(); }
/** * * This method will permanently delete an email from Outlook, similar to * the use of the shift+delete manually on an email in Outlook. * Surprise, surprise...Microsoft does not have a method to easily * perform a PERMANENT DELETE of an email...you literally have to move * the phish eMail to the Deleted Items folder first, and then delete it * from there. This is the only way, at least since the writing of this * comment, that we can permanently delete an email out of Outlook in * Visual C# * */ private void permanentlyDeleteEmail( Microsoft.Office.Interop.Outlook.MailItem currMail) { Microsoft.Office.Interop.Outlook.Explorer currExplorer = Globals.ThisAddIn.Application.ActiveExplorer(); Microsoft.Office.Interop.Outlook.Store store = currExplorer.CurrentFolder.Store; Microsoft.Office.Interop.Outlook.MAPIFolder deletedItemsFolder = store.GetRootFolder().Folders[DELETED_ITEMS_FOLDER_NAME]; // The move here will retain a reference to the MailItem entity that // is moved to the Deleted items folder...this is good because we // don't need to search for this email in Deleted Items...thank the // Maker! Microsoft.Office.Interop.Outlook.MailItem movedMail = currMail.Move(deletedItemsFolder); // Stupid Microsoft action here...need to change a value to trigger a // Save...otherwise, upcoming Delete will NOT OCCUR!!!! movedMail.Subject = movedMail.Subject + " "; // Need to save it... movedMail.Save(); // Now, permanently delete it! movedMail.Delete(); }
public OutlookPortal() { oApp = new Microsoft.Office.Interop.Outlook.Application(); oNameSpace = oApp.GetNamespace("MAPI"); oOutboxFolder = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox); oNameSpace.Logon(null, null, false, false); oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); }
public Outlook() { _ns = _application.Session; _inbox = _ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); _items = _inbox.Items; foreach (var item in _items) { var mail = item as Microsoft.Office.Interop.Outlook.MailItem; var subject = mail.Subject; } }
internal void AddOutLookUsers() { var newUsers = from d in domainUsers where !(from o in outlookUsers select o.NickName) .Contains(d.NickName) select d; Microsoft.Office.Interop.Outlook.MAPIFolder folder = outlookApp.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts); foreach (var user in newUsers) { Microsoft.Office.Interop.Outlook.ContactItem item = (Microsoft.Office.Interop.Outlook.ContactItem)folder.Items.Add(Microsoft.Office.Interop.Outlook.OlItemType.olContactItem); item.MobileTelephoneNumber = user.MobileTelephoneNumber; item.CompanyName = user.CompanyName; item.OfficeLocation = user.OfficeLocation; item.FirstName = user.FirstName; item.ManagerName = user.ManagerName; item.Account = user.Account; item.BusinessTelephoneNumber = user.BusinessTelephoneNumber; item.Department = user.Department; item.FullName = user.FullName; item.Email1Address = user.EmailAddress; item.JobTitle = user.JobTitle; item.LastName = user.LastName; item.NickName = user.NickName; string filename = string.Empty; try { filename = AddPhoto(user.NickName, user.Picture); if (!string.IsNullOrEmpty(filename)) { item.AddPicture(filename); } } catch { } item.Categories = Properties.Settings.Default.Categories; item.Save(); // Cleanup if (!string.IsNullOrEmpty(filename)) { DeletePhoto(filename); } } }
/// <summary> /// Gets a list of all events in outlook /// </summary> public static List <CalendarEvent> GetAllEvents() { List <CalendarEvent> events = new List <CalendarEvent>(); Microsoft.Office.Interop.Outlook.Application oApp = null; Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null; Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null; Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null; oApp = new Microsoft.Office.Interop.Outlook.Application(); mapiNamespace = oApp.GetNamespace("MAPI"); CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); outlookCalendarItems = CalendarFolder.Items; outlookCalendarItems.IncludeRecurrences = true; CalendarEvent cEvent = null; foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems) { cEvent = null; if (item.IsRecurring) { Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern(); DateTime first = new DateTime(2008, 8, 31, item.Start.Hour, item.Start.Minute, 0); DateTime last = new DateTime(2008, 10, 1); Microsoft.Office.Interop.Outlook.AppointmentItem recur = null; for (DateTime cur = first; cur <= last; cur = cur.AddDays(1)) { try { recur = rp.GetOccurrence(cur); cEvent = new CalendarEvent(recur.GlobalAppointmentID, recur.Start, recur.End, recur.Location, recur.Subject, recur.Body); } catch { } } } else { cEvent = new CalendarEvent(item.GlobalAppointmentID, item.Start, item.End, item.Location, item.Subject, item.Body); } if (cEvent != null) { events.Add(cEvent); } } return(events); }
internal void UpdateOutlookUsers() { var updateUsers = from o in outlookUsers from d in domainUsers where o.NickName == d.NickName select new { o, d }; Microsoft.Office.Interop.Outlook.MAPIFolder folder = outlookApp.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts); foreach (var user in updateUsers) { Microsoft.Office.Interop.Outlook.ContactItem item = folder.Items[user.o.Id]; item.MobileTelephoneNumber = user.d.MobileTelephoneNumber; item.CompanyName = user.d.CompanyName; item.OfficeLocation = user.d.OfficeLocation; item.FirstName = user.d.FirstName; item.ManagerName = user.d.ManagerName; item.Account = user.d.Account; item.BusinessTelephoneNumber = user.d.BusinessTelephoneNumber; item.Department = user.d.Department; item.FullName = user.d.FullName; item.Email1Address = user.d.EmailAddress; item.JobTitle = user.d.JobTitle; item.LastName = user.d.LastName; item.NickName = user.d.NickName; string filename = string.Empty; try { filename = AddPhoto(user.d.NickName, user.d.Picture); if (!string.IsNullOrEmpty(filename)) { item.AddPicture(filename); } } catch { } item.Save(); // cleanup if (!string.IsNullOrEmpty(filename)) { DeletePhoto(filename); } } }
static void Main(string[] args) { Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI"); Microsoft.Office.Interop.Outlook.MAPIFolder myContacts = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts); mapiNameSpace.Logon(null, null, false, false);//"*****@*****.**""14March96kr#" mapiNameSpace.Logon(ConfigurationSettings.AppSettings["MailId"], ConfigurationSettings.AppSettings["Password"], Missing.Value, true); Microsoft.Office.Interop.Outlook.Items myItems = myContacts.Items; myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); destFolder = myInbox.Folders["MaliciousAttachments"]; Microsoft.Office.Interop.Outlook.Items inboxItems = myInbox.Items; Microsoft.Office.Interop.Outlook.Explorer myexp = myInbox.GetExplorer(false); mapiNameSpace.Logon("Profile", Missing.Value, false, true); new Program().readingUnReadMailsAsync(inboxItems); }
internal void RemoveOutlookUsers() { var oldUsers = from o in outlookUsers where !(from d in domainUsers select d.NickName) .Contains(o.NickName) orderby o.Id descending select o; Microsoft.Office.Interop.Outlook.MAPIFolder folder = outlookApp.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts); foreach (var user in oldUsers) { folder.Items.Remove(user.Id); } }
/** * * Moves a specified email to a specified destination folder by name. * */ private Microsoft.Office.Interop.Outlook.MailItem moveEmail( Microsoft.Office.Interop.Outlook.MailItem currMail, string destinationFolderName) { Microsoft.Office.Interop.Outlook.Explorer currExplorer = Globals.ThisAddIn.Application.ActiveExplorer(); Microsoft.Office.Interop.Outlook.Store store = currExplorer.CurrentFolder.Store; // Move the current email to User's selected Mail Box... Microsoft.Office.Interop.Outlook.MAPIFolder destFolder = store.GetRootFolder().Folders[destinationFolderName]; return(currMail.Move(destFolder)); }
private void btnRead_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI"); Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); Microsoft.Office.Interop.Outlook.MAPIFolder oPublicFolder = myInbox.Parent; cmbOutlookFolders.Items.Clear(); foreach (Microsoft.Office.Interop.Outlook.MAPIFolder folder in oPublicFolder.Folders) { EnumerateFolders(folder); } cmbOutlookFolders.DisplayMember = "Value"; cmbOutlookFolders.ValueMember = "Key"; }
protected void outlookButton_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Outlook.Application oApp = null; Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null; Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null; Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null; oApp = new Microsoft.Office.Interop.Outlook.Application(); mapiNamespace = oApp.GetNamespace("MAPI");; CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); outlookCalendarItems = CalendarFolder.Items; outlookCalendarItems.IncludeRecurrences = true; allCalendarItemsText.Text = ""; foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems) { allCalendarItemsText.Text += item.Subject + " -> " + item.Start.ToLongDateString(); } }
public static void GetAllTaskItems() { Microsoft.Office.Interop.Outlook.Application oApp = null; Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null; Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null; Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null; oApp = new Microsoft.Office.Interop.Outlook.Application(); mapiNamespace = oApp.GetNamespace("MAPI"); ; CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderTasks); outlookCalendarItems = CalendarFolder.Items; outlookCalendarItems.IncludeRecurrences = true; foreach (Microsoft.Office.Interop.Outlook.TaskItem item in outlookCalendarItems) { if (item.IsRecurring) { //Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern(); //DateTime first = new DateTime(2008, 8, 31, item.Start.Hour, item.Start.Minute, 0); //DateTime last = new DateTime(2008, 10, 1); //Microsoft.Office.Interop.Outlook.AppointmentItem recur = null; //for (DateTime cur = first; cur <= last; cur = cur.AddDays(1)) //{ // try // { // recur = rp.GetOccurrence(cur); // Console.WriteLine(recur.Subject + " -> " + cur.ToLongDateString()); // } // catch // { // } //} } else { Console.WriteLine(item.Subject + " -> " /* + item.Start.ToLongDateString()*/); } } }
public Calendar(int Days, List<String> EMails, String path, String ID) { sendEmail = false; objEntryID = ID; _Days = Days; _EMails = EMails; EmailEvents = new List<EmailEvent>(); // set log path from logPath constant from Main() LOGPATH = path; #if Debug try { #endif objOutlook = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace objNS = objOutlook.GetNamespace("MAPI"); //objEntryID = "000000005BCDA19FC3AF564C9A7D910BCCF3D24642820000"; //String objEntryID = "00000000E6BD34CD1C0FA04DBA1773A312FE25690100E15948BC84BC624E822DC6493E0F48BE0010CCEC4D970000"; objCalendar = objOutlook.Session.GetFolderFromID(objEntryID, System.Type.Missing); #if Debug } catch (Exception ex) { //ToDo: // add handling for exception accessing Outlook System.IO.File.AppendAllText(LOGPATH,DateTime.Now.ToString() + ": " + ex.Message + Environment.NewLine); return; } #endif findEvents(); }
public Outlook() { _ns = _application.Session; _inbox = _ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); _items = _inbox.Items; foreach (var item in _items) { string subject = string.Empty; var mail = item as Microsoft.Office.Interop.Outlook.MailItem; if (mail != null) { var subject = mail.Subject; } else { Debug.WriteLine("Item is not a MailItem"); } } }
private void InitOutlookService() { if (!ifAlreadyInit) { oApp = new Microsoft.Office.Interop.Outlook.Application(); mapiNamespace = oApp.GetNamespace("MAPI"); ; calendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); outlookCalendarItems = calendarFolder.Items; outlookCalendarItems.Sort("[Start]"); outlookCalendarItems.IncludeRecurrences = true; string s1 = GetDateInString(minTime); string s2 = GetDateInString(maxTime); var filterString = "[Start] >= '" + s1 + "' AND [End] < '" + s2 + "'"; outlookCalendarItems = outlookCalendarItems.Restrict(filterString); ifAlreadyInit = true; } }
/// <summary> /// Constructor /// </summary> public OutlookMail() { //Return a reference to the MAPI layer oApp = new Microsoft.Office.Interop.Outlook.Application(); oNameSpace= oApp.GetNamespace("MAPI"); /*********************************************************************** * Logs on the user * Profile: Set to null if using the currently logged on user, or set * to an empty string ("") if you wish to use the default Outlook Profile. * Password: Set to null if using the currently logged on user, or set * to an empty string ("") if you wish to use the default Outlook Profile * password. * ShowDialog: Set to True to display the Outlook Profile dialog box. * NewSession: Set to True to start a new session. Set to False to * use the current session. ***********************************************************************/ oNameSpace.Logon(null,null,true,true); //gets defaultfolder for my Outlook Outbox oSentItems = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail); }
/// <summary> /// Saves an email object of type Microsoft.Office.Interop.Outlook.MailItem to Drafts Box /// </summary> /// <param name="new_message">Microsoft.Office.Interop.Outlook.MailItem object</param> /// <returns>True/False on Success/Failure</returns> protected bool Save_to_Draftbox(_MI_ new_message) { Microsoft.Office.Interop.Outlook.Application app = null; Microsoft.Office.Interop.Outlook._NameSpace nameSpace = null; Microsoft.Office.Interop.Outlook.MAPIFolder drafts = null; try { app = new Microsoft.Office.Interop.Outlook.Application(); nameSpace = app.GetNamespace("MAPI"); nameSpace.Logon(null, null, false, false); drafts = nameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderDrafts); new_message.Save(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(false); } return(true); }
internal void GetOutlookUsers() { Microsoft.Office.Interop.Outlook.MAPIFolder folder = outlookApp.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts); outlookUsers.Clear(); for (int i = folder.Items.Count; i > 0; i--) { try { Microsoft.Office.Interop.Outlook.ContactItem user = folder.Items[i]; if (user.Categories == Properties.Settings.Default.Categories) { var item = new UserDetailsModel { Id = i, MobileTelephoneNumber = user.MobileTelephoneNumber, CompanyName = user.CompanyName, OfficeLocation = user.OfficeLocation, FirstName = user.FirstName, ManagerName = user.ManagerName, Account = user.Account, BusinessTelephoneNumber = user.BusinessTelephoneNumber, Department = user.Department, FullName = user.FullName, EmailAddress = user.Email1Address, JobTitle = user.JobTitle, LastName = user.LastName, NickName = user.NickName, }; outlookUsers.Add(item); } } catch { } } }
private void readInbox(string account, string inbox1, string inbox2) { outlookNamespace.Logon("", "", false, null); Microsoft.Office.Interop.Outlook.MAPIFolder folder = null; try { folder = outlookNamespace.Folders[account].Folders[inbox1]; } catch (Exception) { folder = outlookNamespace.Folders[account].Folders[inbox2]; } foreach (var item in folder.Items) { try { Microsoft.Office.Interop.Outlook.MailItem mailItem = item as Microsoft.Office.Interop.Outlook.MailItem; listBoxEmails.Items.Add(new OutlookEmailItem(mailItem)); } catch (Exception) { } } }
void _OutlookApplication_BeforeFolderSharingDialog(Microsoft.Office.Interop.Outlook.MAPIFolder FolderToShare, ref bool Cancel) { DisplayInWatchWindow(BeforeFolderSharingDialog++, System.Reflection.MethodInfo.GetCurrentMethod().Name); }
void _OutlookApplication_FolderContextMenuDisplay(Microsoft.Office.Core.CommandBar CommandBar, Microsoft.Office.Interop.Outlook.MAPIFolder Folder) { DisplayInWatchWindow(FolderContextMenuDisplay++, System.Reflection.MethodInfo.GetCurrentMethod().Name); }
public void read() { Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace ns = outlook.GetNamespace("Mapi"); object _missing = Type.Missing; ns.Logon(_missing, _missing, false, true); Microsoft.Office.Interop.Outlook.MAPIFolder inbox = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); string foldername = inbox.Name; int iMailCount = inbox.Items.Count; TraceService("Inside read method"); for (int iCount = 1; iCount <= iMailCount; iCount++) { Object mail1 = inbox.Items[iCount]; if (((mail1 as Microsoft.Office.Interop.Outlook.MailItem) != null) && ((mail1 as Microsoft.Office.Interop.Outlook.MailItem).UnRead == true)) { TraceService("Inside unread mail"); Microsoft.Office.Interop.Outlook.MailItem mail = (Microsoft.Office.Interop.Outlook.MailItem)inbox.Items[iCount]; SqlConnection con; string connection = @"server=CSM-DEV\SQL2008;database=TerexBest;uid=sa;pwd=rimc@123"; TraceService("Connection with database done1"); con = new SqlConnection(connection); SqlCommand cmd; cmd = new SqlCommand(); con.Open(); cmd.Connection = con; TraceService("Connection assigned to sql command"); string subject = mail.Subject.ToString(); TraceService("mail subject written" + subject); string body = mail.Body.ToString(); cmd.Parameters.Add("@subject", SqlDbType.NVarChar).Value = subject; TraceService(subject); //writing subject cmd.Parameters.Add("@body", SqlDbType.NVarChar).Value = body; TraceService(body); //writing subject cmd.Parameters.Add("@recievedtime", SqlDbType.DateTime).Value = mail.ReceivedTime; TraceService(mail.ReceivedTime.ToString()); //writing subject cmd.Parameters.Add("@mailfrom", SqlDbType.NVarChar).Value = mail.SenderEmailAddress; TraceService(mail.SenderEmailAddress); //writing subject TraceService("Before Inventory saved"); cmd.CommandText = "insert into storemail(subject,body,createddatetime,mailfrom,isActive) values(@subject,@body,@recievedtime,@mailfrom,1)"; TraceService("Inventory saved"); try { cmd.ExecuteNonQuery(); mail.Delete(); iMailCount = iMailCount - 1; } catch (SqlException ex) { ex.ToString(); } con.Close(); cmd.Dispose(); con.Dispose(); } } GC.Collect(); inbox = null; ns = null; outlook = null; }
public static void UpdateCache(bool resetException = false) { if (resetException) { OutlookException = null; } if (OutlookException != null) { return; } var events = new List <OutlookItem>(); Microsoft.Office.Interop.Outlook.Application oApp = null; Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null; Microsoft.Office.Interop.Outlook.MAPIFolder calendarFolder = null; Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null; try { oApp = new Microsoft.Office.Interop.Outlook.Application(); mapiNamespace = oApp.GetNamespace("MAPI"); calendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); outlookCalendarItems = calendarFolder.Items; outlookCalendarItems.Sort("[Start]"); outlookCalendarItems.IncludeRecurrences = true; //var filter = String.Format("[Start] >= \"{0}\" and [Start] <= \"{1}\"", DateTime.Today, DateTime.Today.AddDays(1)); //outlookCalendarItems = outlookCalendarItems.Find(filter); foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems) { if (item.Start >= CacheRangeStart) { if (item.Start.Date > CacheRangeEnd) { break; } var parsed = LyncMeeting.ParseEmail(item.Body ?? string.Empty, item.Subject); events.Add(new OutlookItem() { Start = item.Start, End = item.End, Subject = item.Subject, LyncMeeting = parsed, OutlookAppointment = item }); } } events = events.OrderBy(e => e.Start).ToList(); lock (Lock) { _cache = events; _cacheLastUpdateTime = DateTime.Now; } } catch (COMException e) { OutlookException = e; } finally { Marshal.ReleaseComObject(oApp); } }
public Outlook(Microsoft.Office.Interop.Outlook.MAPIFolder microsoftOutlook) { MicrosoftOutlook = microsoftOutlook; }
/// <summary> /// Takes an Outlook email object saves the attachemnts /// </summary> /// <param name="email_obj">Microsoft.Office.Interop.Outlook.MailItem object</param> /// <param name="query">String to search for in Subject</param> /// <returns>True/False on Success/Failure</returns> /* protected string Save_Attachments(_MI_ email_obj, bool hasFinalNotices) * { * System.Collections.IEnumerator enumer = email_obj.Attachments.GetEnumerator(); * int count = 1; * * while (enumer.MoveNext()) * { * * if (email_obj.Attachments[count].FileName.Contains(".zip") || email_obj.Attachments[count].FileName.Contains(".ZIP")) * { * email_obj.Attachments[count].SaveAsFile(UNZIP_PATH + email_obj.Attachments[count].FileName); * Console.WriteLine("Saving file as {0}", email_obj.Attachments[count].FileName); * Console.WriteLine("We got the IAVA Finals. Unzipping"); * Console.WriteLine("Attempting to unzip {0}", UNZIP_PATH + email_obj.Attachments[count].FileName); * LocalStorage ls = new LocalStorage(UNZIP_PATH); * string daterange = ls.CreateDateRangeName(); * ls.ExtractZipFile(UNZIP_PATH + email_obj.Attachments[count].FileName, daterange); * return UNZIP_PATH + daterange; * } * count++; * } * * return null; * }*/ /// <summary> /// Search a specified Subfolder in Outlook /// </summary> /// <param name="subfolder_name">Name of Outlook Subfolder to search</param> /// <param name="query">Text to query</param> /// <param name="search_location">Location to search: {(0, Sender), (1, Subject), (2, Body)}</param> /// <param name="only_unread">True/False - Search only Unread Messages/Search All</param> /// <returns>A list of _MI_ objects representing matching emails</returns> private List <_MI_> _Search_Subfolder(string subfolder_name, string query, int search_location, bool only_unread) { List <_MI_> results = new List <_MI_>(); try { Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook._NameSpace nameSpace = null; Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null; Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null; _MI_ item = null; nameSpace = app.GetNamespace("MAPI"); nameSpace.Logon(null, null, false, false); inboxFolder = nameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); try { subFolder = inboxFolder.Folders[subfolder_name]; } catch (Exception not_found) { Console.WriteLine(not_found.ToString()); } for (int i = 1; i <= subFolder.Items.Count; i++) { item = (_MI_)subFolder.Items[i]; query = query.Trim(); switch (search_location) { case 0: Console.WriteLine("Sender: {0}", item.SenderEmailAddress); Console.WriteLine("Other Sender: {0}", item.SenderName); if (item.SenderEmailAddress.ToLower().Contains(query.ToLower())) { if ((only_unread == false) || (only_unread == true && item.UnRead == true)) { results.Add(item); } } break; case 1: if (item.Subject.ToLower().Contains(query.ToLower())) { if ((only_unread == false) || (only_unread == true && item.UnRead == true)) { results.Add(item); } } break; case 2: if (item.Body.ToLower().Contains(query.ToLower())) { if ((only_unread == false) || (only_unread == true && item.UnRead == true)) { results.Add(item); } } break; default: throw new ArgumentException("Error in Query Location"); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return(results); }
/// <summary> /// Metodo que descarga los archivos adjuntos de los correos /// no leidos de la cuenta de outlook /// </summary> public void bandejaEntradaOutlook() { Microsoft.Office.Interop.Outlook.Application app = null; Microsoft.Office.Interop.Outlook._NameSpace ns = null; Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null; Microsoft.Office.Interop.Outlook.MailItem sinLeer; int p = 0, t = 0; while (!detenerHilo) { try { app = new Microsoft.Office.Interop.Outlook.Application(); ns = app.GetNamespace("MAPI"); ns.Logon(null, null, false, false); inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook. OlDefaultFolders.olFolderInbox); ///Se obtiene la bandeja de entrada de la cuenta de correo Microsoft.Office.Interop.Outlook.Items inboxItems = inboxFolder.Items; t = inboxFolder.UnReadItemCount; ///Se obtiene la bandeja de entrada de correos no leidos inboxItems = inboxItems.Restrict("[unread] = true"); while (p < t) { if (p == 0) { ///Se obtiene el primer elemento de la bandeja de entrada sinLeer = inboxItems.GetFirst(); } else { ///Se obtiene el elemento siguiente de la bandeja de entrada sinLeer = inboxItems.GetNext(); } ///Se obtiene los archivos adjuntos del correo Microsoft.Office.Interop.Outlook.Attachments adjuntos = sinLeer.Attachments; foreach (Microsoft.Office.Interop.Outlook.Attachment archivo in adjuntos) { if (ValidarXmlSobre(archivo.FileName)) { ///Se marca el correo como no leido sinLeer.UnRead = false; //Se descargar el archivo adjunto del correo archivo.SaveAsFile(RutasCarpetas.RutaCarpetaBandejaEntrada + archivo.FileName); string desde = sinLeer.Sender.ToString(); //Se sube el archivo al servidor FTP FTP ftp = new FTP(); ftp.CargarArchivos(archivo.FileName, RutasCarpetas.RutaCarpetaBandejaEntrada, 3); //Se guarda en la tabla de sobres Recibidos respuestaSobre.GenerarXML(RutasCarpetas.RutaCarpetaBandejaEntrada, archivo.FileName, desde); } //Se comprueba que sea un ACK else if (ValidarXmlACKSobre(archivo.FileName)) { archivo.SaveAsFile(RutasCarpetas.RutaCarpetaBandejaEntrada); sinLeer.UnRead = false; SobreTransito sobreTransito = ObtenerSobreTransito(archivo.FileName, sinLeer.Sender.ToString()); ManteUdoSobreTransito manteSobreTransito = new ManteUdoSobreTransito(); manteSobreTransito.Almacenar(sobreTransito); } } p = p + 1; } } catch (Exception) { } finally { ns = null; app = null; inboxFolder = null; Thread.Sleep(60000); } } }
public void CreateNewDistributionList(string[] tabAdresse) { Microsoft.Office.Interop.Outlook._Application OutlookApp = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace ns = null; Microsoft.Office.Interop.Outlook.MAPIFolder folderContacts = null; Microsoft.Office.Interop.Outlook.Items contactItems = null; Microsoft.Office.Interop.Outlook.MailItem mail = null; Microsoft.Office.Interop.Outlook.Recipients listRecipients = null; Microsoft.Office.Interop.Outlook.DistListItem distributionList = null; try { string addresseToAdd; ns = OutlookApp.GetNamespace("MAPI"); folderContacts = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts); contactItems = folderContacts.Items; // create a new e-mail message to access the recipients collection mail = contactItems.Add(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as Microsoft.Office.Interop.Outlook.MailItem; mail.To = ""; listRecipients = mail.Recipients; //création de la liste d'adresse foreach (string addresse in tabAdresse) { if (addresse != null) { addresseToAdd = RemoveDiacritics(addresse); listRecipients.Add(addresseToAdd); } } if (!listRecipients.ResolveAll()) { System.Windows.Forms.MessageBox.Show("There are no such contact names. " + "Please make sure that you have corresponding records in your address book", "Add-in Express", MessageBoxButtons.OK, MessageBoxIcon.Warning); } // create a new distribution list item distributionList = contactItems.Add(Microsoft.Office.Interop.Outlook.OlItemType.olDistributionListItem) as Microsoft.Office.Interop.Outlook.DistListItem; distributionList.DLName = "List judo"; distributionList.AddMembers(listRecipients); distributionList.Display(true); } catch (Exception e) { throw new Exception("Erreur Metier.cs/CreateNewDistributionList():\r\n" + e.Message, e); } finally { if (distributionList != null) { Marshal.ReleaseComObject(distributionList); } if (listRecipients != null) { Marshal.ReleaseComObject(listRecipients); } if (mail != null) { mail.Delete(); Marshal.ReleaseComObject(mail); } if (contactItems != null) { Marshal.ReleaseComObject(contactItems); } if (folderContacts != null) { Marshal.ReleaseComObject(folderContacts); } if (ns != null) { Marshal.ReleaseComObject(ns); } } }
public void Dispose() { _disposing = true; ClosePendingSubmitWaitHandles(); if (_items != null) { _items.ItemAdd -= Items_ItemAdd; _items = null; } if (_outbox != null) { ((IDisposable)_outbox).Dispose(); _outbox = null; } if (_ns != null) { ((IDisposable)_ns).Dispose(); _ns = null; } if (_application != null) { ((IDisposable)_application).Dispose(); _application = null; } }