public static ResultadoTransaccion MailEnBorrador(string toValue, string subjectValue, string bodyValue) { ResultadoTransaccion res = new ResultadoTransaccion(); try { oApp = new Application(); oNameSpace = oApp.GetNamespace("MAPI"); oOutboxFolder = oNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderDrafts); _MailItem oMailItem = (_MailItem)oApp.CreateItem(OlItemType.olMailItem); oMailItem.To = toValue; oMailItem.Subject = subjectValue; oMailItem.Body = bodyValue; //oMailItem.SaveSentMessageFolder = oOutboxFolder; oMailItem.BodyFormat = OlBodyFormat.olFormatRichText; oMailItem.Save(); res.Estado = Enums.EstadoTransaccion.Aceptada; } catch (Exception ex) { res.Descripcion = ex.Message; res.Estado = Enums.EstadoTransaccion.Rechazada; Log.EscribirLog(ex.Message); } return(res); }
/* public static ResultadoTransaccion EnviarHTmlEmail(string toValue, string subjectValue, string bodyValue) { ResultadoTransaccion res = new ResultadoTransaccion(); try { oApp = new Application(); oNameSpace = oApp.GetNamespace("MAPI"); oOutboxFolder = oNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderSentMail); _MailItem oMailItem = (_MailItem)oApp.CreateItem(OlItemType.olMailItem); oMailItem.To = toValue; oMailItem.Subject = subjectValue; if (oMailItem.HTMLBody.IndexOf("</BODY>") > -1) oMailItem.HTMLBody = oMailItem.HTMLBody.Replace("</BODY>", bodyValue); oMailItem.SaveSentMessageFolder = oOutboxFolder; oMailItem.BodyFormat = OlBodyFormat.olFormatHTML; oMailItem.Send(); res.Estado = Enums.EstadoTransaccion.Aceptada; } catch (Exception ex) { res.Descripcion = ex.Message; res.Estado = Enums.EstadoTransaccion.Rechazada; Log.EscribirLog(ex.Message); } return res; } */ /// <summary> /// Metodo para el envio de Email desde el Modulo Calendario /// </summary> /// <param name="toValue">Email del receptor</param> /// <param name="subjectValue">Asunto del Email</param> /// <param name="bodyValue">Cuerpo del Email</param> public static ResultadoTransaccion EnviarEmail(string toValue, string subjectValue, string bodyValue) { ResultadoTransaccion res = new ResultadoTransaccion(); try { oApp = new Application(); oNameSpace = oApp.GetNamespace("MAPI"); oOutboxFolder = oNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderSentMail); _MailItem oMailItem = (_MailItem)oApp.CreateItem(OlItemType.olMailItem); oMailItem.To = toValue; oMailItem.Subject = subjectValue; oMailItem.Body = bodyValue; oMailItem.SaveSentMessageFolder = oOutboxFolder; oMailItem.BodyFormat = OlBodyFormat.olFormatRichText; oMailItem.Send(); res.Estado = Enums.EstadoTransaccion.Aceptada; } catch (Exception ex) { res.Descripcion = ex.Message; res.Estado = Enums.EstadoTransaccion.Rechazada; Log.EscribirLog(ex.Message); } return res; }
public void DeleteAllAppointments() { _Application app = null; _NameSpace session = null; MAPIFolder folder = null; Items contactItems = null; app = new Application(); session = app.Session; folder = session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); contactItems = folder.Items; try { //++++++++++++Begin Edit Area+++++++++++++++ foreach (object item in contactItems) { AppointmentItem appointmentItem = item as AppointmentItem; appointmentItem.Delete(); } //++++++++++++End Edit Area+++++++++++++++ } catch (System.Exception ex) { } }
//Search mails in a specified account public static MAPIFolder SearchTargetMailAccount(OutlookApp outlookApp, string accountName) { _NameSpace ns = outlookApp.OutlookAppInstance.GetNamespace("MAPI"); ns.Logon(null, null, false, false); MAPIFolder folder = null; try { Folders folders = outlookApp.OutlookAppInstance.Application.Session.Folders; foreach (MAPIFolder item in folders) { if (item.Name.Contains(accountName)) { folder = item; break; } } } catch (System.Exception ex) { throw new System.Exception(string.Format("Error found when searching the target mail account {0}. The exception message is: {1}", accountName, ex.Message)); } return(folder); }
public static void getCalendarList() { Application app = null; _NameSpace ns = null; MAPIFolder calendarFolder = null; try { app = new Microsoft.Office.Interop.Outlook.Application(); ns = app.GetNamespace("MAPI"); // ns.Logon(null,null,false, false); calendarFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); DateTime today = DateTime.Today, tomorrow = today.AddDays(1); const string DateFormat = "dd/MM/yyyy HH:mm"; string filter = string.Format("[Start] >= '{0}' AND [Start] < '{1}'", today.ToString(DateFormat), tomorrow.ToString(DateFormat)); var todaysAppointments = calendarFolder.Items.Restrict(filter); todaysAppointments.IncludeRecurrences = true; todaysAppointments.Sort("[Start]"); int TotalDurationInMinutes = 0; int acceptedDurationInMinutes = 0; int tentativeDurationInMinutes = 0; int numberOfInvites = todaysAppointments.Count; int acceptedInvites = 0; int tentativeInvites = 0; foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in todaysAppointments) { TotalDurationInMinutes += item.Duration; int responsestatus = 0; if (int.TryParse(item.ResponseStatus.ToString(), out responsestatus)) { if (responsestatus == 1 || responsestatus == 3) { acceptedInvites++; acceptedDurationInMinutes += item.Duration; } else if (responsestatus == 2) { tentativeInvites++; tentativeDurationInMinutes += item.Duration; } } } } catch (System.Runtime.InteropServices.COMException ex) { Console.WriteLine(ex.ToString()); } finally { ns = null; app = null; calendarFolder = null; } }
protected void OpenMessage(string itemId) { Application app = null; _NameSpace ns = null; MailItem item = null; app = new Application(); ns = app.GetNamespace("MAPI"); ns.Logon(null, null, false, false); item = ns.GetItemFromID(itemId); item.Display(); }
public void DeleteAppointments() { _Application app = null; _NameSpace session = null; MAPIFolder folder = null; Items contactItems = null; app = new Application(); session = app.Session; folder = session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); contactItems = folder.Items; var noItemsLeft = false; try { while (noItemsLeft == false) { //++++++++++++Begin Edit Area+++++++++++++++ var n = 0; foreach (object item in contactItems) { if (item != null) { var getType = GetOutlookTypeForComObject(item); if (getType != null && getType.Name == "AppointmentItem") { if ((item as AppointmentItem).Location == "Engage") { n++; (item as AppointmentItem).Delete(); } } } } if (n == 0) { noItemsLeft = true; } //++++++++++++End Edit Area+++++++++++++++ } } catch (System.Exception ex) { if (ex.Message != "The message you specified cannot be found.") // Required because of the MSTO not deleting items completely bug. { MessageBox.Show(ex.Message); } } }
void outlookInit() { try { WaitForReply = new AutoResetEvent(false); app = new Application(); ns = app.GetNamespace("MAPI"); inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); } catch (System.Exception Ex) { BeaconConsole.WriteLine($"Failed to initialize outlook COM: {Ex.Message}"); } }
public MAPIFolder findMailFolder() { Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Accounts accounts = app.Session.Accounts; _NameSpace ns = app.GetNamespace("MAPI"); Folders folders = ns.Folders; MAPIFolder reportsFolder = null; foreach (MAPIFolder f in folders) { if (f.Name == /*"Transport OPS2"*/ "*****@*****.**") { reportsFolder = f; } } return(reportsFolder); }
private MAPIFolder getFolderFromPath(string Path, _NameSpace ns, MAPIFolder parent = null) { if (Path.StartsWith(@"\\")) { Path = Path.Substring(2); } if (Path.EndsWith(@"\")) { Path = Path.Remove(Path.Length - 1); } if (Path.Contains(@"\")) { MAPIFolder parentFolder; string[] subFolders = Path.Split(new char[] { '\\' }, 2); if (parent == null) { parentFolder = ns.Folders[subFolders[0]]; } else { parentFolder = parent.Folders[subFolders[0]]; } return(getFolderFromPath(subFolders[1], ns, parentFolder)); } else { if (parent == null) { return(ns.Folders[Path]); } else { return(parent.Folders[Path]); } } }
static void Main(string[] args) { Application app = null; _NameSpace ns = null; MailItem item = null; MAPIFolder inboxFolder = null; MAPIFolder subFolder = null; try { app = new Application(); ns = app.GetNamespace("MAPI"); ns.Logon(null, null, false, false); inboxFolder = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); subFolder = inboxFolder.Folders["TEST"]; Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID); Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString()); for (int i = 1; i <= subFolder.Items.Count; i++) { item = (MailItem)subFolder.Items[i]; Message message = new Message(item); string json = JsonConvert.SerializeObject(message); IndexLowLevel(json); } //item = ns.GetItemFromID("000000006F8917C81DA08C409D3B1B49454F46C90700C6936CD0FB24CA4482A4BEEF45C1DF1E0000000002100000C6936CD0FB24CA4482A4BEEF45C1DF1E000000001C020000"); //item.Display(); } catch (System.Exception e) { Console.WriteLine(e.ToString()); Console.ReadLine(); } finally { ns = null; app = null; inboxFolder = null; } }
public EmailController() { OpenOutlook(); _ns = GetCOM <_NameSpace>(_outlook.GetNamespace("MAPI")); }
/// <summary> /// Initializes a new instance of the <see cref="OutlookFolderMonitor<T>"/> class. /// </summary> /// <param name="session">The session.</param> /// <param name="folder">The folder to monitor.</param> public OutlookFolderMonitor(_NameSpace session, MAPIFolder folder) { _deletedItemsFolder = session.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems); HookupFolderEvents(folder); }
static void Main(string[] args) { Console.WriteLine("*******************************************************"); Console.WriteLine("Invalid Email Address identification Process Started..."); Console.WriteLine("*******************************************************\n\n"); //Intialize variables Application outlookApplication = null; _NameSpace outlookNameSpace = null; MAPIFolder inboxFolder = null; MAPIFolder workingFolder = null; MAPIFolder processedReportFolder = null; MAPIFolder processedMailFolder = null; MAPIFolder exceptionReportFolder = null; MAPIFolder exceptionMailFolder = null; int totalOutlookItems; int totalMailItems; int totalReportItems; List <MailItem> MailItemList = new List <MailItem>(); List <ReportItem> ReportItemList = new List <ReportItem>(); Console.WriteLine("Required variables Intialized...\n\n"); try { //Logon to outlook Application using default profile outlookApplication = new Application(); outlookNameSpace = outlookApplication.GetNamespace("MAPI"); outlookNameSpace.AddStore(""); outlookNameSpace.Logon(null, null, false, false); //first value null as Default outlook profile //Set working folders inboxFolder = outlookNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderInbox); workingFolder = inboxFolder.Folders["Working Folder"]; //folder.Folders[1]; also works processedReportFolder = workingFolder.Folders["Done Folder"].Folders["Report Items Folder"]; //assuming folders are in working folder processedMailFolder = workingFolder.Folders["Done Folder"].Folders["Mail Items Folder"]; //assuming folders are in working folder exceptionReportFolder = workingFolder.Folders["Error Folder"].Folders["Report Items Folder"]; //assuming folders are in working folder exceptionMailFolder = workingFolder.Folders["Error Folder"].Folders["Mail Items Folder"]; //assuming folders are in working folder // Displaying All Folders Console.WriteLine("Inbox Folder: {0},\n Working Folder: {1},\n Processed Folder: {2} & {3},\n Exception Folder: {4} & {5}", inboxFolder.Name, workingFolder.Name, processedReportFolder.Name, processedMailFolder.Name, exceptionReportFolder.Name, exceptionMailFolder.Name); totalOutlookItems = workingFolder.Items.Count; Console.WriteLine("\tComplete number of Items found: {0}", totalOutlookItems.ToString()); #region doingStuff // only run when some outlook items are found if (totalOutlookItems > 0) { //Saves List of all Mail Items foreach (MailItem myitem in workingFolder.Items.OfType <MailItem>()) { MailItemList.Add(myitem); } totalMailItems = MailItemList.Count; Console.WriteLine("\t\tMail Items found: {0}", totalMailItems.ToString()); //Saves List of all Report Items foreach (ReportItem myitem in workingFolder.Items.OfType <ReportItem>()) { ReportItemList.Add(myitem); } totalReportItems = ReportItemList.Count; Console.WriteLine("\t\tReport Items found: {0}", totalReportItems.ToString()); //Pause //Console.ReadKey(); //Processing of //Invalid Email //Address new ExtractData().GetMailItemsData(MailItemList, processedMailFolder, exceptionMailFolder); new ExtractData().GetReportItemsData(ReportItemList, processedReportFolder, exceptionReportFolder); } else { Console.WriteLine("\nNo Outlook item found for processing."); } #endregion doingStuff } catch (System.Runtime.InteropServices.COMException ex) { Console.WriteLine(ex.ToString()); } finally { Console.WriteLine("\nLogging Off...\n"); outlookNameSpace.Logoff(); outlookNameSpace = null; outlookApplication = null; inboxFolder = null; Console.WriteLine("Process Ended. Press any key to close this Black Window..."); //Console.ReadKey(); } }
public ResultadoTransaccion EnviarMaiSalesLead(ClsSalesLead salesLead) { var res = new ResultadoTransaccion(); try { oApp = new Application(); oNameSpace = oApp.GetNamespace("MAPI"); oOutboxFolder = oNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderSentMail); var mail = (_MailItem)oApp.CreateItem(OlItemType.olMailItem); var body = CrearCuerpoMailSalesLead(salesLead, Path.Combine(System.Windows.Forms.Application.StartupPath, @"mailSalesLead\template.html")); if (!string.IsNullOrEmpty(mail.HTMLBody) && mail.HTMLBody.ToLower().Contains("</body>")) { var imagePath = Path.Combine(System.Windows.Forms.Application.StartupPath, @"mailSalesLead\logo.png"); mail.Subject = "New Sales Lead"; //mail.To = salesLead.Agente.Email; mail.To = salesLead.Agente.Email; //CONTENT-ID const string schemaPrAttachContentId = @"http://schemas.microsoft.com/mapi/proptag/0x3712001E"; var contentId = Guid.NewGuid().ToString(); mail.Attachments.Add(imagePath, OlAttachmentType.olEmbeddeditem, mail.HTMLBody.Length, Type.Missing); mail.Attachments[mail.Attachments.Count].PropertyAccessor.SetProperty(schemaPrAttachContentId, contentId); //Create and add banner body = body.Replace("[logo]", string.Format(@"<img src=""cid:{1}"" />", "", contentId)); if (mail.HTMLBody.IndexOf("</BODY>") > -1) mail.HTMLBody = mail.HTMLBody.Replace("</BODY>", body); mail.Display(true); } } catch (Exception e) { res.Descripcion = e.Message; res.Estado = Enums.EstadoTransaccion.Rechazada; Log.EscribirLog(e.Message); } return res; }
public static MailItem GetEmail(string subject, string recipientEmail, DateTime maxAgeTimeStamp, int waitSeconds) { const int checkIntervalSeconds = 15; const string prSmtpAddress = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"; if (Process.GetProcessesByName("outlook").Length == 0) { Process.Start("outlook.exe"); } var item = new MailItem(); NetOffice.OutlookApi.MailItem oItem = null; var match = false; try { Application app = new Application(); _NameSpace ns = app.GetNamespace("MAPI"); ns.Logon(null, null, false, false); MAPIFolder inboxFolder = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); _Items oItems = inboxFolder.Items; oItems.Sort("[ReceivedTime]", false); Console.WriteLine("DBG: Started looking for email at {0}", DateTime.Now); for (int j = 0; j <= waitSeconds; j = j + checkIntervalSeconds) { Thread.Sleep(TimeSpan.FromSeconds(checkIntervalSeconds)); for (int i = oItems.Count; i > 1; i--) { oItem = (NetOffice.OutlookApi.MailItem)oItems[i]; Console.WriteLine("DBG: Checking mail at {0} => found mail with timestamp: { 1}", DateTime.Now.ToLongTimeString(), oItem.SentOn.ToLongTimeString()); if ((oItem.ReceivedTime - maxAgeTimeStamp).TotalSeconds < 0) { break; } if (oItem.Subject.IsRegExMatch(subject) && oItem.Recipients.Single().PropertyAccessor.GetProperty(prSmtpAddress).ToString().Equals(recipientEmail)) { match = true; break; } //Console.WriteLine("Subject: {0}", item.Subject); //Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString()); } if (match) { break; } } } catch (System.Runtime.InteropServices.COMException) { throw new Exception("ERROR: retrieving the email failed due to System.Runtime.InteropServices.COMException"); } if (match) { item.EntryId = oItem.EntryID; item.Subject = oItem.Subject; item.SentDate = oItem.SentOn.ToLongDateString(); item.SentTime = oItem.SentOn.ToLongTimeString(); item.ReceivedDate = oItem.ReceivedTime.ToLongDateString(); item.ReceivedTime = oItem.ReceivedTime.ToLongTimeString(); item.Body = oItem.Body; item.HtmlBody = oItem.HTMLBody; item.HasMessage = true; item.PrintInfo(); } else { Console.WriteLine("DBG: Couldn't find message with subject matching {0} and recipient {1}", subject, recipientEmail); } Console.WriteLine("DBG: Finished looking for email at {0}", DateTime.Now); return(item); }
/// <summary> /// This method scans a single mail item against all criteria to determine if the mail item needs to be moved. /// If so then it moves the mail item to the specified target outlook folder for the first set of criteria that it matches. /// </summary> private bool ScanAll(_NameSpace nameSpace, MailItem mailItem, string sender, string subject, string body, ref int movedItemsCount, out bool anyCriteriaApplied) { bool anyPasses = false; anyCriteriaApplied = false; SignalBeginScan(Administrator.ProfileManager.UserSettings.Entries.Count); foreach (var pair in Administrator.ProfileManager.UserSettings.Entries) { if (Interrupt.Reason != "Cancel") { SignalUpdateScan(1); bool criteriaDisplayed = false; UserSetting userSetting = pair.Value; string[] parts = userSetting.Folder.Split(Path.DirectorySeparatorChar); MAPIFolder targetFolder = null; try { targetFolder = nameSpace.Folders[parts[0]]; for (int ptr = 1; ptr < parts.Length; ptr++) { targetFolder = targetFolder.Folders[parts[ptr]]; } } catch (System.Exception ex) { Administrator.Tracer.WriteTimedMsg("E", ex.Message); targetFolder = null; } if (targetFolder != null) { string fullPath = targetFolder.FullFolderPath; string shortPath = targetFolder.FolderPath; string name = targetFolder.Name; string senderCriteria = string.Empty; Scanner senderScanner = null; if (userSetting.SenderCriteria.Trim().Length > 0) { senderCriteria = Clean(userSetting.SenderCriteria); senderScanner = new Scanner(senderCriteria); } string subjectCriteria = string.Empty; Scanner subjectScanner = null; if (userSetting.SubjectCriteria.Trim().Length > 0) { subjectCriteria = Clean(userSetting.SubjectCriteria); subjectScanner = new Scanner(subjectCriteria); } string bodyCriteria = string.Empty; Scanner bodyScanner = null; if (userSetting.BodyCriteria.Trim().Length > 0) { bodyCriteria = Clean(userSetting.BodyCriteria); bodyScanner = new Scanner(bodyCriteria); } bool criteriaApplied = false; string prefix = string.Empty; bool pass = Scan(sender, subject, body, senderScanner, subjectScanner, bodyScanner, out criteriaApplied, out prefix); anyPasses |= pass; anyCriteriaApplied |= criteriaApplied; if (criteriaApplied && pass) { if (!criteriaDisplayed) { criteriaDisplayed = true; Administrator.Tracer.WriteLine(); Administrator.Tracer.WriteMsg("I", String.Format(@"Folder : ""{0}""", userSetting.Folder)); if (senderCriteria.Trim().Length > 0) { Administrator.Tracer.WriteTimedMsg("I", String.Format(@"Sender Criteria = {0}", senderCriteria)); } else { Administrator.Tracer.WriteTimedMsg("I", "Sender Criteria = None"); } if (subjectCriteria.Trim().Length > 0) { Administrator.Tracer.WriteTimedMsg("I", String.Format(@"Subject Criteria = {0}", subjectCriteria)); } else { Administrator.Tracer.WriteTimedMsg("I", "Subject Criteria = None"); } if (bodyCriteria.Trim().Length > 0) { Administrator.Tracer.WriteTimedMsg("I", String.Format(@"Body Criteria = {0}", bodyCriteria)); } else { Administrator.Tracer.WriteTimedMsg("I", "Body Criteria = None"); } Administrator.Tracer.WriteLine(); } Administrator.Tracer.WriteTimedMsg("I", String.Format(@"Matched [{0}] Moving -> Sender : ""{1}"", Subject : ""{2}""", prefix, sender, subject)); mailItem.Move(targetFolder); movedItemsCount++; //No need to check any further criteria as the mail item has already been matched to a preceding criteria and moved. break; } } } else { break; } } SignalEndOfScan(Administrator.ProfileManager.UserSettings.Entries.Count); return(anyPasses); }
public ResultadoTransaccion EnviarMailCotizacionDirecta(String subject, String html, List<String> pathAdjuntos) { var res = new ResultadoTransaccion(); try { oApp = new Application(); oNameSpace = oApp.GetNamespace("MAPI"); oOutboxFolder = oNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderSentMail); var mail = (_MailItem)oApp.CreateItem(OlItemType.olMailItem); mail.Subject = subject; mail.HTMLBody = html; //mail.Attachments.Add(foo, OlAttachmentType.olByValue, mail.HTMLBody.Length, Type.Missing); if (pathAdjuntos != null) foreach (var adj in pathAdjuntos) mail.Attachments.Add((object)adj, OlAttachmentType.olEmbeddeditem, 1, (object)"Attachment"); mail.Save(); mail.Display(false); } catch (Exception e) { res.Descripcion = e.Message; res.Estado = Enums.EstadoTransaccion.Rechazada; Log.EscribirLog(e.Message); } return res; }