/// <summary> /// Open an item in outlook folder /// </summary> /// <param name="item">Outlook item used to open</param> public static void DisplayAndCloseItem(object item) { try { Outlook.Application outlookApp = new Outlook.Application(); object[] args = new object[] { }; object retVal = item.GetType().InvokeMember("Class", BindingFlags.Public | BindingFlags.GetField | BindingFlags.GetProperty, null, item, args); Outlook.OlObjectClass outlookItemClass = (Outlook.OlObjectClass)retVal; switch (outlookItemClass) { case Outlook.OlObjectClass.olMail: Outlook.MailItem omail = (Outlook.MailItem)item; omail.Display(false); omail.Close(Outlook.OlInspectorClose.olSave); break; case Outlook.OlObjectClass.olDocument: Outlook.DocumentItem odocument = (Outlook.DocumentItem)item; odocument.Display(true); odocument.Close(Outlook.OlInspectorClose.olSave); break; case Outlook.OlObjectClass.olRecurrencePattern: default: break; } } catch (Exception e) { throw new Exception(e.Message); } }
private void buttonClose_Click(object sender, EventArgs e) { try { Outlook.MailItem mailItem = null; try { if ((mailItem = OutlookItem as Outlook.MailItem) != null) { mailItem.Close(Outlook.OlInspectorClose.olDiscard); } } finally { if (mailItem != null) { Marshal.ReleaseComObject(mailItem); mailItem = null; } } } catch (Exception eException) { string msg; ThisAddIn.WriteToLog(msg = eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + (eException.InnerException != null && !string.IsNullOrEmpty(eException.InnerException.Message) ? "InnerException.Message" + eException.InnerException.Message + Environment.NewLine : string.Empty) + "StackTrace:" + Environment.NewLine + eException.StackTrace); textBoxLog.Text = msg; } }
public bool AtualizarMailItem(string categories, string entryId) { bool ret = false; try { Outlook.Application myApp = new Outlook.Application(); Outlook._NameSpace mapiNameSpace = myApp.GetNamespace("MAPI"); Outlook.MAPIFolder fd = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); string storeId = fd.StoreID; Outlook.MailItem mailItem = mapiNameSpace.GetItemFromID(entryId, storeId) as Outlook.MailItem; mailItem.Categories = categories; mailItem.Close(Outlook.OlInspectorClose.olSave); myApp.Quit(); ret = true; } catch (Exception ex) { throw ex; } return(ret); }
private void create_Email_Draft(String filename, String master, String house) { try { Outlook.Application outlookApp = new Outlook.Application(); Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem); mailItem.Subject = "Test Subject"; mailItem.To = "*****@*****.**"; mailItem.Body = "Hi ! This is a test message"; mailItem.Importance = Outlook.OlImportance.olImportanceLow; mailItem.Display(false); if (string.IsNullOrEmpty(filename) == false) { // need to check to see if file exists before we attach ! if (!File.Exists(filename)) { MessageBox.Show("Attached document " + filename + " does not exist", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { mailItem.Attachments.Add(filename, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); mailItem.Attachments.Add(master, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); mailItem.Attachments.Add(house, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); } } mailItem.Close(Outlook.OlInspectorClose.olSave); } catch (Exception ex) { throw new Exception("Error occured trying to create email item --- " + Environment.NewLine + ex.Message); } }
private void ApproveBtn_Click(object sender, RibbonControlEventArgs e) { Outlook.MailItem email = ThisEmail(); email.Save(); XLMain.Client client = XLMain.Client.FetchClient(XLOutlook.ReadParameter("CrmID", email)); XLMain.Staff writer = XLMain.Staff.StaffFromUser(Environment.UserName); if (XLantRibbon.staff.Count == 0) { XLantRibbon.staff = XLMain.Staff.AllStaff(); } StaffSelectForm myForm = new StaffSelectForm(client, writer, XLantRibbon.staff); myForm.ShowDialog(); XLMain.EntityCouplet staff = myForm.selectedStaff; string commandfileloc = ""; string fileId = XLOutlook.ReadParameter("VCFileID", email); commandfileloc = XLVirtualCabinet.Reindex(fileId, staff.name, status: "Approved", docDate: DateTime.Now.ToString("dd/MM/yyyy")); XLVirtualCabinet.BondResult result = XLVirtualCabinet.LaunchCabi(commandfileloc, true); if (result.ExitCode != 0) { MessageBox.Show("Reindex failed please complete manually."); } else { // Close the email in Outlook to prevent further changes that won't be saved to VC email.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olSave); // Delete the email from the Drafts folder in Outlook // email.Delete(); } }
public static void AssignTicket(Outlook.MailItem mailItem, string email) { if (mailItem != null) { if (!Properties.Settings.Default.NoAssignConf) { DialogResult confirm = MessageBox.Show("Assign Ticket to " + email + "?\nSubject: " + mailItem.Subject, "Spiceworks Outlook AddIn", MessageBoxButtons.YesNo); if (confirm == DialogResult.Yes) { try { Outlook.MailItem newMsg = mailItem.Reply(); newMsg.Body = "#assign to " + email; newMsg.Send(); if (Properties.Settings.Default.CloseMsg) { mailItem.Close(Outlook.OlInspectorClose.olPromptForSave); } } catch (Exception e) { MessageBox.Show("Unable to assign ticket. Error: " + e.ToString() , "Spiceworks Outlook AddIn", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } else { try { Outlook.MailItem newMsg = mailItem.Reply(); newMsg.Body = "#assign to " + email; newMsg.Send(); if (Properties.Settings.Default.CloseMsg) { mailItem.Close(Outlook.OlInspectorClose.olPromptForSave); } } catch (Exception e) { MessageBox.Show("Unable to assign ticket. Error: " + e.ToString() , "Spiceworks Outlook AddIn", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } }
public void BtnBackupEmail_Click(Office.IRibbonControl control) { Outlook.MailItem mailItem = null; Outlook.Explorer explorer = null; Outlook.Inspector inspector = null; if (ControlIsInInspector(control, ref inspector) == true) { mailItem = inspector.CurrentItem as Outlook.MailItem; if (mailItem != null) { if (BackupEmailUtil.IsEmailAlreadyInBackupFolder(mailItem)) { mailItem.Close(Outlook.OlInspectorClose.olSave); } else { BackupEmailUtil.MarkEmailReadAndClearAllCategories(mailItem); EmailFlagUtil.FlagEmail(mailItem); BackupEmailUtil.BackupEmail(mailItem); } } } else if (ControlIsInExplorer(control, ref explorer) == true) { try { // I have to wrap 'explorer.selction' into a try block, // becasue outlook will raise an exception on this line when the first page is 'Outlook Today' Outlook.Selection selection = explorer.Selection; foreach (var selected in selection) { mailItem = selected as Outlook.MailItem; if (mailItem != null) { if (BackupEmailUtil.IsEmailAlreadyInBackupFolder(mailItem) == false) { EmailFlagUtil.FlagEmail(mailItem); } } } foreach (var selected in selection) { mailItem = selected as Outlook.MailItem; if (mailItem != null) { if (BackupEmailUtil.IsEmailAlreadyInBackupFolder(mailItem) == false) { BackupEmailUtil.MarkEmailReadAndClearAllCategories(mailItem); BackupEmailUtil.BackupEmail(mailItem); } } } } catch (COMException ex) { Debug.WriteLine(ex.ToString()); } } }
private EMail GetMailStruct(string displayName, string address, string type) { EMail result = new EMail(); //if no valid mail data exit without calc if ((type ?? "") == "") { return(result); } result.Title = displayName; result.Address = null; //if SMTP-address is given if (type.ToUpper() == "SMTP") { result.Address = address; } //if EXCHANGE-address else if (type.ToUpper() == "EX") { Microsoft.Office.Interop.Outlook.MailItem tmpMail = null; try { tmpMail = mAPI.Application.CreateItem(OutlookInterop.OlItemType.olMailItem); tmpMail.To = address; if (tmpMail.Recipients.ResolveAll()) { foreach (OutlookInterop.Recipient tmpRcip in tmpMail.Recipients) { OutlookInterop.ExchangeUser exchangeUser = tmpRcip.AddressEntry.GetExchangeUser(); if (exchangeUser != null) { result.Address = exchangeUser.PrimarySmtpAddress; } } } } catch (Exception e) { Debug.WriteLine("ERROR GetMailStruct " + e.Message); } finally { if (tmpMail != null) { tmpMail.Close(OutlookInterop.OlInspectorClose.olDiscard); } tmpMail = null; } } return(result); }
// Method for sending a phishing report while viewing target suspicous message in Outlook private void SendPhishingReport(Outlook.Inspector Inspector) { try { // Proceed with attempting to send the submission Outlook.MailItem phish_mail = Inspector.CurrentItem as Outlook.MailItem; Outlook.MailItem mail = Application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; DateTime phish_date = DateTime.Now; mail.Subject = "New Phishing Report " + phish_date.ToString(); Outlook.AddressEntry currentUser = Application.Session.CurrentUser.AddressEntry; // Target e-mail address (which will receive the phishing report) is defined in the associated config file variable, "ReportTargetEmail" // // You can also replace all instances of "Properties.Settings.Default.ReportTargetEmail" with a hard-coded string literal (or string variable name) if you'd prefer to not use the config file. // Example: mail.Recipients.Add("*****@*****.**"); mail.Recipients.Add(Properties.Settings.Default.ReportTargetEmail); mail.Recipients.ResolveAll(); mail.Attachments.Add(phish_mail, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); mail.Send(); Debug.WriteLine(String.Format("{0} PIE Button: Phishing report submitted", DateTime.Now)); // Notify the end-user that the submission was sent DialogResult ds = MessageBox.Show(String.Format("Phishing report successfully submitted to: {0}\n\nThank you!", Properties.Settings.Default.ReportTargetEmail), "Report Phishing - Submission Success", MessageBoxButtons.OK, MessageBoxIcon.Information); // Close the suspicous message in Outlook explorer phish_mail.Close(Outlook.OlInspectorClose.olDiscard); Debug.WriteLine(String.Format("{0} PIEButton: Closed suspicious message", DateTime.Now)); return; } catch (Exception ex) { // An error has occurred Debug.Write(String.Format("PIEButton: {0}", ex.ToString())); return; } }
public static bool OutlookConverter(string srcfile) { try { var format = Outlook.OlSaveAsType.olHTML; var desfile = srcfile.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries)[0] + ".html"; var outlook = new Outlook.Application(); Outlook.MailItem opf = outlook.Session.OpenSharedItem(srcfile); opf.SaveAs(desfile, format); opf.Close(Outlook.OlInspectorClose.olDiscard); outlook.Quit(); Marshal.ReleaseComObject(opf); Marshal.ReleaseComObject(outlook); if (opf != null) { ReleaseRCM(opf); } if (outlook != null) { ReleaseRCM(outlook); } opf = null; outlook = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } catch (Exception ex) { //System.Windows.MessageBox.Show(ex.ToString()); return(false); } return(true); }
public static void CloseTicketWithResponse(Outlook.MailItem mailItem) { if (mailItem != null) { try { Outlook.MailItem newMsg = mailItem.Reply(); newMsg.Body = "\n\n#close" + newMsg.Body; newMsg.Display(); if (Properties.Settings.Default.CloseMsg) { mailItem.Close(Outlook.OlInspectorClose.olPromptForSave); } } catch (Exception e) { MessageBox.Show("Unable to close ticket. Error: " + e.ToString() , "Spiceworks Outlook Addin", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
/// <summary> /// WrapperEvent fired when a mailItem is closed. /// </summary> /// <param name="mailItem">the mailItem to close</param> /// <param name="Cancel">False when the event occurs. If the event procedure sets this argument to True, /// the open operation is not completed and the inspector is not displayed.</param> void mailItem_Close(Outlook.MailItem mailItem, ref bool Cancel) { try { if (mailItem == null) return; // New mail (Compose) if (mailItem.Sent == false) { var toSave = false; var signProperpty = GetProperty(mailItem, "GnuPGSetting.Sign"); if (signProperpty == null || (bool)signProperpty != _ribbon.SignButton.Checked) { toSave = true; } var encryptProperpty = GetProperty(mailItem, "GnuPGSetting.Decrypted"); if (encryptProperpty == null || (bool)encryptProperpty != _ribbon.EncryptButton.Checked) { toSave = true; } if (toSave) { #if DISABLED BoolEventArgs ev = e as BoolEventArgs; DialogResult res = MessageBox.Show("Do you want to save changes?", "OutlookGnuPG", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation); if (res == DialogResult.Yes) { // Must call mailItem.Write event handler (mailItem_Save) explicitely as it is not always called // from the mailItem.Save() method. Mail is effectly saved only if a property changed. mailItem_Save(sender, EventArgs.Empty); mailItem.Save(); } if (res == DialogResult.Cancel) { ev.Value = true; } #else // Invalidate the mailItem to force Outlook to ask to save the mailItem, hence calling // the mailItem_Save() handler to record the buttons state. // Note: the reason (button state property change) to save the mailItem is not necessairy obvious // to the user, certainly if nothing has been updated/changed by the user. If specific notification // is required see DISABLED code above. Beware, it might open 2 dialog boxes: the add-in custom and // the regular Outlook save confirmation. mailItem.Subject = mailItem.Subject; } #endif } else { var signProperty = GetProperty(mailItem, "GnuPGSetting.Decrypted"); if (signProperty != null && (bool)signProperty) { mailItem.Close(Outlook.OlInspectorClose.olDiscard); } } } catch { // Ignore random COM errors } }
public static void ForwardMessage(Outlook.MailItem mailItem) { if (mailItem != null) { if (!Properties.Settings.Default.NoForwardConf) { DialogResult confirm = MessageBox.Show("Create Ticket?\nSubject: " + mailItem.Subject, "Spiceworks Outlook AddIn", MessageBoxButtons.YesNo); if (confirm == DialogResult.Yes) { string recipient = Properties.Settings.Default.HelpdeskEmail; if (recipient == "" || recipient == null) { MessageBox.Show("Unable to forward message to Spiceworks. Please check that 'Helpdesk Email' is set in Settings." , "Spiceworks Outlook AddIn", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { try { Outlook.MailItem newMsg = mailItem.Forward(); newMsg.Subject = mailItem.Subject; newMsg.Body += "\n\n#created by " + Logic.GetSenderSMTPAddress(mailItem); newMsg.Recipients.Add(recipient); newMsg.Send(); if (Properties.Settings.Default.CloseMsg) { mailItem.Close(Outlook.OlInspectorClose.olPromptForSave); } } catch { MessageBox.Show("Unable to forward message to Spiceworks. Please check that 'Helpdesk Email' is set in Settings." , "Spiceworks Outlook AddIn", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } else { string recipient = Properties.Settings.Default.HelpdeskEmail; if (recipient == "" || recipient == null) { MessageBox.Show("Unable to forward message to Spiceworks. Please check that 'Helpdesk Email' is set in Settings." , "Spiceworks Outlook AddIn", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { try { Outlook.MailItem newMsg = mailItem.Forward(); newMsg.Subject = mailItem.Subject; newMsg.Body += "\n\n#created by " + Logic.GetSenderSMTPAddress(mailItem); newMsg.Recipients.Add(recipient); newMsg.Send(); if (Properties.Settings.Default.CloseMsg) { mailItem.Close(Outlook.OlInspectorClose.olPromptForSave); } } catch { MessageBox.Show("Unable to forward message to Spiceworks. Please check that 'Helpdesk Email' is set in Settings." , "Spiceworks Outlook AddIn", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } }
int processMail(object oMsg) { if (oMsg == null) { return(-1); } int foundAttachements = 0; if (oMsg == null) { return(-2); } Outlook.MailItem mitem = oMsg as Outlook.MailItem; if (mitem == null) { return(-3); } if (mitem.Subject != null) { helpers.addLog(string.Format("looking at: {0}\n", mitem.Subject)); } else { helpers.addLog(string.Format("looking at: {0}\n", mitem.EntryID)); } if (mitem.Attachments.Count == 0) { return(-4); } else { //look for .xml foreach (Outlook.Attachment att in mitem.Attachments) { if (att.FileName.EndsWith("xml")) { foundAttachements++; } } if (foundAttachements == 0) { return(-5); //no attachement ending in xml } } if (mitem.Subject.IndexOf(helpers.filterSubject) == -1) { return(-6); } if (mitem.Subject.IndexOf(sMailHasAlreadyProcessed) >= 0) //do not process mail again { return(-7); } //process mail helpers.addLog(string.Format("### mail found: {0},\n{1}\n\n", mitem.Subject, mitem.Body)); OnStateChanged(new StatusEventArgs(StatusType.ews_pulse, "getMail: processing eMail " + mitem.Subject)); MailMsg myMailMsg = new MailMsg(mitem, _userData.sUser); int iRet = _licenseMail.processMail(myMailMsg); //change subject if (mitem.Subject.IndexOf(sMailHasAlreadyProcessed) == -1) { mitem.Subject += sMailHasAlreadyProcessed; mitem.Close(Outlook.OlInspectorClose.olSave); } OnStateChanged(new StatusEventArgs(StatusType.license_mail, "processed " + iRet.ToString())); Thread.Sleep(100); Thread.Yield(); return(iRet); }
/// <summary> /// Convert EML file to DOC using Outlook interop /// </summary> /// <param name="emlFile">Path to EML file to convert</param> /// <param name="tempPath">Path that function can use as temporary write/read location</param> /// <param name="docPath">Path to write DOC file to</param> /// <returns>True on creation of DOC file, otherwise false</returns> static bool EmlToDoc(string emlFile, string tempPath, string docPath) { bool success = false; var guid = Guid.NewGuid(); string guidStr = guid.ToString(); byte[] guidBytes = Encoding.ASCII.GetBytes(guidStr); byte[] emlData = System.IO.File.ReadAllBytes(emlFile); byte[] returnPathPattern = new byte[] { 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x2D, 0x50, 0x61, 0x74, 0x68, 0x3A }; byte[] subjectPattern = new byte[] { 0x0D, 0x0A, 0x53, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74, 0x3A, 0x20 }; byte[] nextLinePattern = new byte[] { 0x0D, 0x0A }; List <byte> subjectBuffer = new List <byte>(); // TODO does not handle where Subject: is first line of file string originalSubject = ""; int lastPos = -1; int indexOfSubject = IndexOf(subjectPattern, emlData, 0); if (indexOfSubject >= 0) { lastPos = indexOfSubject + subjectPattern.Length; int nextLine = IndexOf(nextLinePattern, emlData, lastPos); while (nextLine > 0) { for (int i = lastPos; i < nextLine; ++i) { subjectBuffer.Add(emlData[i]); } lastPos = nextLine + 2; if (!IsLWSP(emlData, lastPos)) { break; } nextLine = IndexOf(nextLinePattern, emlData, lastPos); } originalSubject = System.Text.Encoding.UTF8.GetString(subjectBuffer.ToArray()); } using (var stream = new FileStream(tempPath, FileMode.Create)) { if (indexOfSubject >= 0) { // write data from start to end of Subject header stream.Write(emlData, 0, indexOfSubject + subjectPattern.Length); } else { // inject subject to begining of stream stream.Write(subjectPattern, 2, subjectPattern.Length - 2); lastPos = 0; } // write guide stream.Write(guidBytes, 0, guidBytes.Length); stream.WriteByte(0x0D); stream.WriteByte(0x0A); // write remaining data stream.Write(emlData, lastPos, emlData.Length - lastPos); } ProcessStartInfo psi = new ProcessStartInfo(tempPath); psi.UseShellExecute = true; psi.CreateNoWindow = true; Process p = Process.Start(psi); //Thread.Sleep(100); Outlook.Application outlook = new Outlook.Application(); Outlook.MailItem mailItem = null; int maxAttemptsToFindItem = 100; do { try { Outlook.Inspectors inspectors = outlook.Inspectors; foreach (Outlook.Inspector inspector in inspectors) { if (inspector == null) { continue; } mailItem = (Outlook.MailItem)inspector.CurrentItem; if (mailItem == null) { continue; } string mailItemSubject = mailItem.Subject; if (mailItemSubject != null && mailItemSubject.CompareTo(guidStr) == 0) { mailItem.Subject = originalSubject; mailItem.SaveAs(docPath, Outlook.OlSaveAsType.olDoc); success = true; mailItem.Close(Outlook.OlInspectorClose.olDiscard); } } } catch (System.Exception e) { Console.WriteLine("{0}\n{1}", emlFile, e); } --maxAttemptsToFindItem; } while (!success && maxAttemptsToFindItem > 0); if (!success && maxAttemptsToFindItem == 0) { Console.WriteLine("{0} max attempts exceeded", emlFile); } return(success); }
public static void IndexDraft(Outlook.MailItem email) { try { XLant.XLVirtualCabinet.BondResult outcome = IndexEmail(email, "Draft"); if (outcome.ExitCode != 0) { MessageBox.Show("Unable to index document, please index manually. Error code: " + outcome.ExitCode.ToString() + "-" + outcome.StandardOutput.ToString()); } else { UpdateVCTick(email); // As the filing has been successfull, get the FileId returned from Bond via the Standard Output string fileid = Regex.Match(outcome.StandardOutput, @"\d+").ToString(); string folderpath = XLtools.TempPath(); string commandfilepath = ""; commandfilepath = folderpath + "\\" + (String.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now)) + ".bond"; StreamWriter commandfile = new StreamWriter(commandfilepath, false, System.Text.Encoding.Default); commandfile.WriteLine("<<MODE=EDIT>>"); commandfile.WriteLine("<<INDEX01=" + fileid + ">>"); commandfile.WriteLine("<<OPENDOCUMENT=FALSE>>"); commandfile.Flush(); commandfile.Close(); // Call Bond to check out the document XLVirtualCabinet.BondResult result = XLVirtualCabinet.LaunchCabi(commandfilepath, false); // Dispose of the command file object commandfile.Dispose(); // Look for the file in the edited documents folder based on the FileId List <string> msgfile = new List <string>(); string[] Files = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Virtual Cabinet\\Edited documents"); int FilesCount = Files.Length; // Collect all the entries which match the fileID for (int i = 0; i < FilesCount; i++) { string f = Files[i].ToString(); if (Path.GetFileName(f).StartsWith(fileid + "-")) { msgfile.Add(f); } } if (msgfile.Count != 1) { Exception exception = new Exception("Unable to find the mail message. Your file has been indexed but could not have the file ID added."); } else { // Add the Virtual Cabinet FileId to the Subject of the email (still open on screen) // UserProperties and Custom Headers do not persist, so using something that does. Body could be another option. XLOutlook.UpdateParameter("VCFileID", fileid, email); //email.Subject = email.Subject + @" FileId:" + fileid.ToString(); // Save the MailItem email.Save(); // Save the email in the default MSG format if (File.Exists(msgfile[0])) { File.Delete(msgfile[0]); } email.SaveAs(msgfile[0]); // Create a command file to save the document as a new version based on the FileId commandfilepath = folderpath + "\\" + (String.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now)) + ".bond"; commandfile = new StreamWriter(commandfilepath, false, System.Text.Encoding.Default); commandfile.WriteLine("<<MODE=SAVE>>"); commandfile.WriteLine("<<INDEX01=" + fileid + ">>"); commandfile.Flush(); commandfile.Close(); // Call Bond to save the email back to VC result = XLVirtualCabinet.LaunchCabi(commandfilepath, false); // Dispose of the command file object commandfile.Dispose(); // Close the email in Outlook to prevent further changes that won't be saved to VC email.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olSave); // Delete the email from the Drafts folder in Outlook email.UnRead = false; email.Delete(); } } } catch (Exception ex) { MessageBox.Show("Unable to index draft email"); XLtools.LogException("IndexDraft", ex.ToString()); } }
public static void OverwriteDraft(Outlook.MailItem email) { try { //get the fileID from the stored Parameter string fileId = XLOutlook.ReadParameter("VCFileID", email); //reindex the email to remove the to be actioned by and update status and doc date string commandfileloc = ""; commandfileloc = XLVirtualCabinet.Reindex(fileId, status: "Sent", docDate: email.SentOn.ToString("dd/MM/yyyy")); XLVirtualCabinet.BondResult result = XLVirtualCabinet.LaunchCabi(commandfileloc, true); if (result.ExitCode != 0) { MessageBox.Show("Reindex failed please complete manually."); } else { //If reindex successful then continue //create a commandfile to reopen the email in edit mode string folderpath = XLtools.TempPath(); string commandfilepath = ""; commandfilepath = folderpath + "\\" + (String.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now)) + ".bond"; StreamWriter commandfile = new StreamWriter(commandfilepath, false, System.Text.Encoding.Default); commandfile.WriteLine("<<MODE=EDIT>>"); commandfile.WriteLine("<<INDEX01=" + fileId + ">>"); commandfile.WriteLine("<<OPENDOCUMENT=FALSE>>"); commandfile.Flush(); commandfile.Close(); // Call Bond to check out the document result = XLVirtualCabinet.LaunchCabi(commandfilepath, false); // Dispose of the command file object commandfile.Dispose(); // Look for the file in the edited documents folder based on the FileId List <string> msgfile = new List <string>(); string[] Files = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Virtual Cabinet\\Edited documents"); int FilesCount = Files.Length; // Collect all the entries which match the fileID for (int i = 0; i < FilesCount; i++) { string f = Files[i].ToString(); if (Path.GetFileName(f).StartsWith(fileId + "-")) { msgfile.Add(f); } } //There should only be 1 if there are more something has gone wrong. We don't want to overwrite the wrong one so exit if (msgfile.Count != 1) { Exception exception = new Exception("Unable to find the draft email message."); } else { // Delete the old version and save the sent email in the default MSG format if (File.Exists(msgfile[0])) { File.Delete(msgfile[0]); } email.SaveAs(msgfile[0]); // Create a command file to save the document as a new version based on the FileId commandfilepath = folderpath + "\\" + (String.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now)) + ".bond"; commandfile = new StreamWriter(commandfilepath, false, System.Text.Encoding.Default); commandfile.WriteLine("<<MODE=SAVE>>"); commandfile.WriteLine("<<INDEX01=" + fileId + ">>"); commandfile.Flush(); commandfile.Close(); // Call Bond to save the email back to VC result = XLVirtualCabinet.LaunchCabi(commandfilepath, false); // Dispose of the command file object commandfile.Dispose(); //update the tick box UpdateVCTick(email); //Mark email as saved. email.UnRead = false; //Close and save email.Close(Outlook.OlInspectorClose.olSave); } } } catch (Exception ex) { MessageBox.Show("Unable to update e-mail"); XLtools.LogException("OverwriteDraft", ex.ToString()); } }
private static void MailParser(Outlook.MailItem mail) { #region E-Mail Filter /// <summary> /// Creates a list read from text file of e-mail addresses of senders, later if the sender is on this list the program will do stuff else it will ignore e-mail. /// </summary> List <string> filter = new List <string>(); //New list to hold e-mail addresses to check try { if (File.Exists(@"c:\User Programs\filter.txt")) //populates the list if the text file exists { using (StreamReader sr = new StreamReader(@"c:\User Programs\filter.txt")) // the streamreader will auto close the text file when done reading. { while (sr.Peek() >= 0) //reads until the end of the file, peek checks the next line for content. { filter.Add(sr.ReadLine()); } } } else //If the text file didn't exist asks the user to create one { MessageBox.Show(@"Please define a text file at C:\User Programs\filter.txt insert salesman names you'd like to run manifold program for one on each line"); } } catch { } #endregion bool tester = filter.Any(name => mail.SenderEmailAddress.ToUpper().Contains(name.ToUpper())); //Create a bool object to check if the mail sender is one of the names in the filter file if (tester) //If the sender is one of the filter names then continue more checks, otherwise will ignore the e-mail { try { var attachments = mail.Attachments; //Pull out the attachments to read pdf sales orders var attachmentMatches = new List <string>(); if (attachments.Count > 0) { string tempPdf = System.IO.Path.GetTempFileName(); for (int i = 1; i <= mail.Attachments.Count; i++) { if (mail.Attachments[i].FileName.Contains(".pdf")) { mail.Attachments[i].SaveAsFile(tempPdf); List <string> tempAttachments = Attachment(tempPdf); if (tempAttachments.Count > 0) { attachmentMatches.AddRange(tempAttachments); } } } File.Delete(tempPdf); } // Find manifold PN's in the e-mail body with regular expressions MatchCollection matches = Regex.Matches(mail.Body, @"\d\d?\w+-\d\d?-.+?(?=\s)", RegexOptions.IgnoreCase); // was having problem with passing matches so change to string string[] output = new string[attachmentMatches.Count + matches.Count]; if (matches.Count > 0) { for (int i = 0; i < matches.Count; i++) { output[i] = matches[i].ToString(); } } if (attachmentMatches.Count > 0) { for (int i = 0; i < attachmentMatches.Count; i++) { output[i + matches.Count] = attachmentMatches[i]; } } if (output.Count() > 0) { ProcessStartInfo startInfo = new ProcessStartInfo(); // code to pass arguments to manifoldlister. Console menu to open manifolds. startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = "ManifoldLister.exe"; const string argsSeparator = " "; string args = string.Join(argsSeparator, output); startInfo.Arguments = args; try { Process.Start(startInfo); } catch (Exception) { MessageBox.Show("Was not able to start ManifoldLister.exe"); } } //OpenFolder(output); } catch (Exception) { } } mail.Close(Outlook.OlInspectorClose.olDiscard); GC.Collect(); }
public string GetExistingSig() { string signature = ""; // Create the Outlook application. // Create a new mail item. Microsoft.Office.Interop.Word.Bookmark bkm = null; Microsoft.Office.Interop.Word.Bookmarks bkms = null; Microsoft.Office.Interop.Word.Document document = null; Outlook.Inspector inspector = null; Outlook.MailItem oMsg = null; try { oMsg = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem); //Add an attachment. inspector = oMsg.GetInspector; document = (Microsoft.Office.Interop.Word.Document)inspector.WordEditor; document.Bookmarks.ShowHidden = true; bkms = document.Bookmarks; bkms.ShowHidden = true; } catch (System.Exception) { Console.WriteLine("[!] Couldn't get Outlook COM object"); return(null); } try { try { bkm = bkms["_MailAutoSig"]; } catch (System.Exception ex) { // skip the exception } if (bkm != null) { Microsoft.Office.Interop.Word.Range bkmRange = bkm.Range; var bkmText = bkmRange.Text; if (string.IsNullOrWhiteSpace(bkmText)) { Console.WriteLine("Signature Empty"); } else { //At this point, we know there is a signature already present - the text of the signature is stored in bkmText Console.WriteLine("Existing Signature is: " + bkmText); } signature = bkmText.ToString(); Marshal.ReleaseComObject(bkmRange); bkmRange = null; Marshal.ReleaseComObject(bkm); bkm = null; } else { Console.WriteLine("No Signature"); } } catch (System.Exception ee) { Console.WriteLine("Couldn't get existing signature from email body: " + ee.Message); } try { oMsg.Close(OlInspectorClose.olDiscard); document.Close(WdSaveOptions.wdDoNotSaveChanges); inspector.Close(OlInspectorClose.olDiscard); } catch (System.Exception) { Console.WriteLine("Couldn't close Outlook inspector."); } try { } catch (System.Exception) { Console.WriteLine("Couldn't close Word doc from signature inspection"); } return(signature); }