public static void RemoveCategoryFromMailITem(String tag, Outlook.MailItem mi) { if (tag.Equals(mi.Categories)) { mi.Categories = ""; mi.Save(); } else { if (mi.Categories.StartsWith(tag + ", ")) { mi.Categories = mi.Categories.Replace(tag + ", ", ""); mi.Save(); } if (mi.Categories.Contains(", " + tag + ", ")) { mi.Categories = mi.Categories.Replace(", " + tag + ", ", ", "); mi.Save(); } if (mi.Categories.EndsWith(", " + tag)) { mi.Categories = mi.Categories.Replace(", " + tag, ""); mi.Save(); } } }
/// <summary> /// Отправка данных на веб сервис для создания заявки. /// </summary> /// <param name="destinationUrl">Ссылка на веб сервис</param> /// <param name="requestXml">XML данные</param> public void postXMLData(string destinationUrl, string requestXml) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl); byte[] bytes; bytes = System.Text.Encoding.UTF8.GetBytes(requestXml); request.ContentType = "text/xml; encoding='utf-8'"; request.ContentLength = bytes.Length; request.Method = "POST"; request.UserAgent = "AddIns by DeAmouSE"; Stream requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) { Stream responseStream = response.GetResponseStream(); string responseStr = new StreamReader(responseStream).ReadToEnd(); XDocument xdoc = XDocument.Parse(responseStr); if (xdoc.Element("result").Element("error") != null) { string errorText = xdoc.Element("result").Element("error").Value; if (errorText != "") { MessageBox.Show(errorText, "Ошибка при создании заявки", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); return; } } string taskId = xdoc.Element("result").Element("taskId").Value; if (taskId != "") { MessageBox.Show(string.Format("Создана заявка {0}. Ссылка на заявку скопирована в буфер обмена", taskId), "Заявка успешно создана", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); Clipboard.SetText(string.Format("http://servicedesk.gradient.ru/Task/View/{0}", taskId)); if (Settings.Default.CategoryMail != "") { if (mailItem.Categories == null) { mailItem.Categories = Settings.Default.CategoryMail; mailItem.Save(); } if (mailItem.Categories.Contains(Settings.Default.CategoryMail) == false) { mailItem.Categories += Settings.Default.CategoryMail; mailItem.Save(); } } } else { MessageBox.Show("Странная ошибка, очень странная...", "Ошибка при создании заявки", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); } } } catch (Exception e) { MessageBox.Show(e.Message, "Ошибка при создании заявки", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); } }
public static void AddCategoryToMailItem(Outlook.MailItem mi, String tag, Outlook.Application application) { CategoryUtils.EnsureCategoryExists(tag, application); String categoriesString = mi.Categories; if (null == categoriesString || "".Equals(categoriesString)) { mi.Categories = tag;// adding first category mi.Save(); } else { // some categories already assigned String[] cats = categoriesString.Split(','); bool categoryAlreadyAssociated = false; foreach (String cat in cats) { if (cat.Equals(tag)) { categoryAlreadyAssociated = true; } } if (categoryAlreadyAssociated) { // don't change anything } else { mi.Categories = categoriesString + "," + tag; mi.Save(); } } }
public void NewNoteAndForward() { // Create two new note Outlook.NoteItem oNote1 = Utilities.NewNote("Note1"); Outlook.NoteItem oNote2 = Utilities.NewNote("Note2"); // Create a simple mail Outlook.MailItem omail = Utilities.CreateSimpleEmail("Attach Note"); // Add the new note as an attach for new created mail Outlook.MailItem omailWithAttach = Utilities.AddAttachsToEmail(omail, new object[] { oNote1, oNote2 }); omailWithAttach.Save(); omailWithAttach = Utilities.RemoveAttachsToEmail(omailWithAttach); // Send mail Utilities.SendEmail(omailWithAttach); // Get the latest send mail from send mail folder Outlook.MailItem omailSend = Utilities.GetNewestItemInMAPIFolder(sentMailFolder, "Attach Note"); Utilities.DeleteAllItemInMAPIFolder(sentMailFolder); // Parse the saved trace using MAPI Inspector List <string> allRopLists = new List <string>(); bool result = false; result = MessageParser.ParseMessage(out allRopLists); // Update the XML file for the covered message Utilities.UpdateXMLFile(allRopLists); // Assert failed if the parsed result has error Assert.IsTrue(result, "Case failed, check the details information in error.txt file."); }
private void CreateMultipleMailItem(string subject, string recipient, List <string> accounts, List <string> filepath, string asof, string title) { Outlook.Application app = new Outlook.Application(); Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem); mailItem.Subject = title + " Quarterly Statements"; mailItem.To = subject; string body = recipient + ", <br/> Attached is the quarterly statement for period ended " + asof + " for the following accounts: <br/>"; foreach (var item in accounts) { string account = item + "<br/>"; body = body + account; } mailItem.HTMLBody = body + "<br/>" + ReadSignature(); foreach (var item in filepath) { if (item.Length > 0) { mailItem.Attachments.Add(item, Outlook.OlAttachmentType.olByValue, 1, Path.GetFileName(item)); } } mailItem.Importance = Outlook.OlImportance.olImportanceLow; mailItem.Save(); mailItem.UnRead = true; Console.WriteLine("Mail Item created for: " + recipient + ", Email: " + subject); }
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 void OnCategoriesAction(Office.IRibbonControl control) { Outlook.Inspector inspector = null; if (ControlIsInInspector(control, ref inspector) == true) { Outlook.MailItem mailItem = inspector.CurrentItem as Outlook.MailItem; if (mailItem != null) { mailItem.Categories = ""; mailItem.Categories = control.Tag; mailItem.Save(); } return; } Outlook.Explorer explorer = null; if (ControlIsInExplorer(control, ref explorer) == true) { Outlook.Selection selection = explorer.Selection; foreach (var selected in selection) { Outlook.MailItem mailItem = selected as Outlook.MailItem; if (mailItem != null) { mailItem.Categories = ""; mailItem.Categories = control.Tag; mailItem.Save(); } } return; } }
public bool SendMail(DbEmail email) { Outlook.Attachment oAttach; try { // Create the Outlook application by using inline initialization. Outlook.Application oApp = new Outlook.Application(); //Create the new message by using the simplest approach. Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); //Add a recipient Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add(email.Recipient); oRecip.Resolve(); //Set the basic properties. oMsg.Subject = email.Subject; oMsg.Body = email.Body; //Add an attachment //if (email.Attachments.Count > 0) //{ // for (int i = 0; i < email.Attachments.Count(); i++) // { // String sSource = email.Attachments[i]; // String sDisplayName = email.Subject; // int iPosition = (int)oMsg.Body.Length + 1; // int iAttachType = (int)Outlook.OlAttachmentType.olByValue; // oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName); // } //} // If you want to, display the message. // oMsg.Display(true); //modal //Send the message. oMsg.Save(); //(oMsg as _Outlook.MailItem).Send(); //Outlook.Account account = oApp.Session.Accounts[email.Sender]; //oMsg.SendUsingAccount = account; ((Outlook._MailItem)oMsg).Send(); //Explicitly release objects. oRecip = null; oAttach = null; oMsg = null; oApp = null; return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); //Label1.Text = ex.Message + ex.StackTrace; return(false); } }
private void SetMailItemUserProperty(Outlook.MailItem mailItem, object item) { Outlook.UserProperties mailUserProperties = mailItem.UserProperties; Outlook.UserProperty propJobMetaData = null; try { // Where 1 is OlFormatText (introduced in Outlook 2007) propJobMetaData = mailUserProperties.Add("JobMetaData", Outlook.OlUserPropertyType.olText, false, 1); //IList<Recruiter.JobItem> list = iRecruiter.IncludedJobItems.Values.ToList(); string temp = JsonConvert.SerializeObject(item); propJobMetaData.Value = temp; //propJobMetaData.Value = htmlResults; mailItem.Save(); // } catch (Exception) { //MessageBox.Show( ex.Message ); } finally { if (propJobMetaData != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(propJobMetaData); } if (propJobMetaData != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(mailUserProperties); } } // }
public static void UpdateVCTick(Outlook.MailItem email) { try { Outlook.ItemProperties properties = email.ItemProperties; if (properties.Cast <Outlook.ItemProperty>().Where(c => c.Name == "In Virtual Cabinet").Count() == 0) { properties.Add("In Virtual Cabinet", Outlook.OlUserPropertyType.olYesNo); } properties["In Virtual Cabinet"].Value = 1; //Change category //check there isn't already a category assigned if (email.Categories == null) { //discover the VC category and assign it string catName = OutlookCategory(); if (catName != null) { var vCCat = catName; email.Categories = vCCat; } } email.Save(); } catch (Exception ex) { //MessageBox.Show("Unable to update parameter"); XLtools.LogException("Outlook-UpdateParameter", ex.ToString()); } }
private static void DeleteAttachment(Outlook.MailItem mailItem) { int count = mailItem.Attachments.Count; int keepCount = 0; for (int i = 0; i < count; ++i) { if (AttachmentIsInlineImage(mailItem, mailItem.Attachments[1 + keepCount]) == false) { string fileName = ""; try { fileName = mailItem.Attachments[1 + keepCount].FileName; } catch { // can not get the fileename, then ignore this attachment. } if (fileName != "") { mailItem.Attachments[1 + keepCount].Delete(); mailItem.Save(); } else { ++keepCount; } } else { ++keepCount; } } }
private static void AddAttachmentLinkToBodyEndAndSaveToDisk(Outlook.MailItem mailItem) { if (mailItem.Attachments.Count > 0) { string attachmentLinks = ""; for (int i = 1; i <= mailItem.Attachments.Count; ++i) { if (AttachmentIsInlineImage(mailItem, mailItem.Attachments[i]) == false) { if (attachmentLinks == "") { attachmentLinks += @"<div>======== Saved attachment links ========<br>"; } string fileName = ""; try { fileName = mailItem.Attachments[i].FileName; } catch { // can not get the file name, then ignore this attachment. } if (fileName != "") { string location = Config.AttachmentBackupPath + (Config.AttachmentBackupPath.EndsWith(@"\") ? "" : @"\") + mailItem.Attachments[i].FileName; try { mailItem.Attachments[i].SaveAsFile(location); } catch (FileLoadException) { location = Path.GetFileNameWithoutExtension(mailItem.Attachments[i].FileName); location += @"@___@" + Util.MakeValidFileName(mailItem.Subject); location += @"@___@" + Util.MakeValidFileName(mailItem.ReceivedTime.ToString()); location += Path.GetExtension(mailItem.Attachments[i].FileName); location = Config.AttachmentBackupPath + (Config.AttachmentBackupPath.EndsWith(@"\") ? "" : @"\") + location; mailItem.Attachments[i].SaveAsFile(location); } string uri = Regex.Replace(location, @"\\", @"/", RegexOptions.IgnoreCase); attachmentLinks += "<a href=\"file:///" + uri + "\">" + uri + @"</a><br>"; } } } if (attachmentLinks != "") { attachmentLinks += @"========================================</div>"; mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML; mailItem.HTMLBody = Regex.Replace(mailItem.HTMLBody, @"</body>", @"<br>" + attachmentLinks + @"</body>", RegexOptions.IgnoreCase); mailItem.Save(); } } }
private void Application_NewMail(string EntryID) { try { var objItem = Globals.ThisAddIn.Application.Session.GetItemFromID(EntryID); if (objItem is Outlook.MailItem) { Outlook.MailItem objMail = (Outlook.MailItem)objItem; if (objMail.UserProperties["SuiteCRM"] == null) { ArchiveEmail(objMail, 2, this.settings.ExcludedEmails); objMail.UserProperties.Add("SuiteCRM", Outlook.OlUserPropertyType.olText, true, Outlook.OlUserPropertyType.olText); objMail.UserProperties["SuiteCRM"].Value = "True"; objMail.Save(); } } } catch (Exception ex) { string strLog; strLog = "------------------" + System.DateTime.Now.ToString() + "-----------------\n"; strLog += "Application_NewMail General Exception:" + "\n"; strLog += "Message:" + ex.Message + "\n"; strLog += "Source:" + ex.Source + "\n"; strLog += "StackTrace:" + ex.StackTrace + "\n"; strLog += "Data:" + ex.Data.ToString() + "\n"; strLog += "HResult:" + ex.HResult.ToString() + "\n"; strLog += "-------------------------------------------------------------------------" + "\n"; clsSuiteCRMHelper.WriteLog(strLog); } }
private void Application_ItemSend(object item, ref bool target) { try { if (item is Outlook.MailItem) { Outlook.MailItem objMail = (Outlook.MailItem)item; if (objMail.UserProperties["SuiteCRM"] == null) { ArchiveEmail(objMail, 3, this.settings.ExcludedEmails); objMail.UserProperties.Add("SuiteCRM", Outlook.OlUserPropertyType.olText, true, Outlook.OlUserPropertyType.olText); objMail.UserProperties["SuiteCRM"].Value = "True"; objMail.Save(); } } } catch (Exception ex) { string strLog; strLog = "------------------" + System.DateTime.Now.ToString() + "-----------------\n"; strLog += "OutlookEvents_ItemSend General Exception:" + "\n"; strLog += "Message:" + ex.Message + "\n"; strLog += "Source:" + ex.Source + "\n"; strLog += "StackTrace:" + ex.StackTrace + "\n"; strLog += "Data:" + ex.Data.ToString() + "\n"; strLog += "HResult:" + ex.HResult.ToString() + "\n"; strLog += "-------------------------------------------------------------------------" + "\n"; clsSuiteCRMHelper.WriteLog(strLog); } }
// CopyTo CopyFolder GetNuffer TellVersion Destination public void NewMailAndMoveToSubPublicFolder() { // Create a simple mail and save Outlook.MailItem omailOne = Utilities.CreateSimpleEmail("FastTransferCopyTo"); omailOne.Save(); // Create a simple mail and save Outlook.MailItem omailTwo = Utilities.CreateSimpleEmail("FastTransferCopyTo"); omailTwo.Save(); // Get first user folder in All public folder publicFolders = oApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olPublicFoldersAllPublicFolders); Outlook.MAPIFolder firstUserFolder = Utilities.GetUserFolderInAllPublicFolder(publicFolders); // Add a subfoler named testFolder under the firstUserFolder Outlook.MAPIFolder testFolder = Utilities.AddSubFolder(firstUserFolder, "testFolder"); // Move the new created mail to public folder omailOne.Copy().Move(testFolder); omailTwo.Copy().Move(testFolder); testFolder.CopyTo(inboxFolders); // Delete all subfolders in firstUserFolder Utilities.RemoveAllSubFolders(firstUserFolder, false); // Delete all subfolders in inboxFolders Utilities.RemoveAllSubFolders(inboxFolders, false); bool result = MessageParser.ParseMessage(); Assert.IsTrue(result, "Case failed, check the details information in error.txt file."); }
/// <summary> /// Update items properties /// </summary> /// <param name="item">The target item</param> public static void UpdateItemProperties(object item) { try { 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.Categories = "黄色类别"; omail.Save(); break; case Outlook.OlObjectClass.olDocument: Outlook.DocumentItem odocument = (Outlook.DocumentItem)item; odocument.Categories = "黄色类别"; odocument.Save(); break; default: break; } } catch (Exception e) { throw new Exception(e.Message); } }
private void buttonMarkAll_Click(object sender, RibbonControlEventArgs e) { if (!_folders.Any()) { groupMarkAll_DialogLauncherClick(sender, e); return; } Task.Run(() => { foreach (var folder in _folders) { var folderItems = folder.Items.Restrict("[Unread]=true"); for (int m = folderItems.Count; m > 0; m--) { Outlook.MailItem mail = folderItems[m]; if (mail.UnRead) { mail.UnRead = false; mail.Save(); } Marshal.ReleaseComObject(mail); } Marshal.ReleaseComObject(folderItems); } }); }
private void SaveMailItemIfNecessary(Outlook.MailItem o, string type) { if (type == "SendArchive") { o.Save(); } }
private void buttonSetHeader_Click(object sender, EventArgs e) { string newValue; if (string.IsNullOrEmpty(newValue = textBoxLog.Text.Trim())) { return; } try { Outlook.MailItem mailItem = null; try { if ((mailItem = OutlookItem as Outlook.MailItem) != null) { string TransportMessageHeadersSchema = #if !TRANSPORT_MESSAGE_HEADERS_W PR_TRANSPORT_MESSAGE_HEADERS #else PR_TRANSPORT_MESSAGE_HEADERS_W #endif , header = (string)mailItem.PropertyAccessor.GetProperty(TransportMessageHeadersSchema); Regex regex = new Regex(string.Format("(?<=^{0}:\\s).*?(?=$)", headerKey), RegexOptions.Multiline | RegexOptions.IgnoreCase); Match match = regex.Match(header); if (match.Success) { header = regex.Replace(header, newValue); mailItem.PropertyAccessor.SetProperty(TransportMessageHeadersSchema, header); mailItem.Save(); } } } 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; } }
private void buttonAddAttach_Click(object sender, EventArgs e) { try { Outlook.MailItem mailItem = null; try { if ((mailItem = OutlookItem as Outlook.MailItem) != null) { mailItem.Attachments.Add("d:\\test.txt", Outlook.OlAttachmentType.olByValue, 1, "Test Attachment"); mailItem.Save(); } } 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 override void SendEmail(string recipient, string cc, string bcc, string subject, string body) { ol.Application olApp = new ol.Application(); ol.MailItem eMail = (ol.MailItem)olApp.CreateItem(ol.OlItemType.olMailItem); eMail.To = recipient; eMail.CC = cc; eMail.BCC = bcc; eMail.Subject = subject; eMail.BodyFormat = (body.StartsWith("<html", StringComparison.CurrentCultureIgnoreCase)) ? ol.OlBodyFormat.olFormatHTML : ol.OlBodyFormat.olFormatPlain; if (eMail.BodyFormat == ol.OlBodyFormat.olFormatHTML) { eMail.HTMLBody = body; } if (eMail.BodyFormat == ol.OlBodyFormat.olFormatPlain) { eMail.Body = body; } if (AutoSend) { eMail.Send(); } else { eMail.Save(); eMail.Display(false); } Marshal.ReleaseComObject(eMail); eMail = null; }
/// <summary> /// Save this email item, of this type, to CRM. /// </summary> /// <param name="mailItem">The email item to send.</param> /// <param name="type">?unknown</param> /// <returns>An archive result comprising the CRM id of the email, if stored, /// and a list of exceptions encountered in the process.</returns> public ArchiveResult SaveEmailToCrm(Outlook.MailItem mailItem, string type) { ArchiveResult result; try { SaveMailItemIfNecessary(mailItem, type); result = ConstructAndDespatchCrmItem(mailItem, type); if (!String.IsNullOrEmpty(result.EmailId)) { /* we successfully saved the email item itself */ mailItem.Categories = "SuiteCRM"; mailItem.Save(); if (mailItem.Attachments.Count > 0) { result = ConstructAndDespatchAttachments(mailItem, result); } } } catch (System.Exception failure) { Log.Warn("Could not upload email to CRM", failure); result = ArchiveResult.Failure(failure); } return(result); }
private void SaveMailItemIfNecessary(Outlook.MailItem olItem, EmailArchiveReason reason) { if (reason == EmailArchiveReason.SendAndArchive) { olItem.Save(); } }
public void SendEmail(string contacts, string subject, string body, bool htmlFormat) { try { this.StartOutlook(); Outlook.Application outlook = new Outlook.Application(); Outlook.MailItem message = (Outlook.MailItem)outlook.CreateItem(Outlook.OlItemType.olMailItem); message.To = contacts; message.Subject = subject; if (htmlFormat) { message.HTMLBody = body; } else { message.Body = body; } message.Save(); message.Send(); } catch (System.Exception e) { Console.WriteLine("{0} Exception caught: ", e); } }
public void MoveMailToSameMailboxFolder() { // Create a simple mail and save Outlook.MailItem omail = Utilities.CreateSimpleEmail("ImportMessageMove"); omail.Save(); bool unread = omail.UnRead; Thread.Sleep(20000); omail.UnRead = !unread; Thread.Sleep(20000); omail.Save(); Thread.Sleep(20000); // Add a sub-folder named testFolder under the draftsFolders Outlook.MAPIFolder testFolder = Utilities.AddSubFolder(draftsFolders, "testFolder"); // Move mails in draftsFolder to testFolder omail.Move(testFolder); // Get the latest mail from testFolder folder Outlook.MailItem omailInTestFolder = Utilities.GetNewestItemInMAPIFolder(testFolder, "ImportMessageMove"); omailInTestFolder.Delete(); int count = 0; while (testFolder.Items.Count != 0) { Thread.Sleep(TestBase.waittimeItem); count += TestBase.waittimeItem; if (count >= TestBase.waittimeWindow) { break; } } // Delete all sub-folders in draftsFolder Utilities.RemoveAllSubFolders(TestBase.draftsFolders, true); // Parse the saved trace using MAPI Inspector List <string> allRopLists = new List <string>(); bool result = MessageParser.ParseMessage(out allRopLists); // Update the XML file for the covered message Utilities.UpdateXMLFile(allRopLists); // Assert failed if the parsed result has error Assert.IsTrue(result, "Case failed, check the details information in error.txt file."); }
internal static void FlagEmail(Outlook.MailItem mailItem) { if (IsMailItemHasFlaggedPreviousMail(mailItem) == true) { mailItem.MarkAsTask(Outlook.OlMarkInterval.olMarkNoDate); mailItem.Save(); } }
/// <summary> /// An Outlook item doesn't get its entry ID until the first time it's saved; if I don't have one, save me. /// </summary> /// <param name="olItem">Me</param> /// <returns>My entry id.</returns> public static string EnsureEntryID(this Outlook.MailItem olItem) { if (olItem.EntryID == null) { olItem.Save(); } return(olItem.EntryID); }
private void buttonApply_Click(object sender, EventArgs e) { buttonApply.Enabled = false; buttonPreview.Enabled = false; OutlookHelperTool.setMailText(mailitem, tempMessage); OutlookHelperTool.cutCryptedSubject(mailitem); mailitem.Save(); this.Close(); }
private static void ClearMailItemFlagIfItsInSentItemFolder(Outlook.MailItem mailItem) { Outlook.Folder parentFolder = mailItem.Parent as Outlook.Folder; Debug.Assert(parentFolder != null); if (parentFolder.FolderPath.EndsWith("\\Sent Items")) { mailItem.ClearTaskFlag(); mailItem.Save(); } }
public void newMailItemAdded(Outlook.MailItem mail) { string cats = mail.Categories; cats += getAttachmentCategories(mail.Attachments); cats += getSenderCategory(mail.SenderName); cats += getConversationCategories(mail); mail.Categories = getUniqueTags(cats); mail.Save(); }
private void CopyBody(ref AppointmentItem ai, MailItem mailItem) { ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem enter"); Word.Document Doc = new Word.Document(); Word.Document Doc2 = new Word.Document(); //Doc = Globals.ThisAddIn.Application.ActiveInspector().WordEditor as Word.Document; Doc = ai.GetInspector.WordEditor as Word.Document; //Doc = g_currentAppointItem.GetInspector.WordEditor as Word.Document; if (Doc != null) { ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length)); Doc.Activate(); Doc.Select(); //App1 = Doc.Windows.Application; //Sel = App1.Selection; //Sel.WholeStory(); //Sel.Copy(); Doc.Range().WholeStory(); Doc.Range().Copy(); Doc2 = mailItem.GetInspector.WordEditor as Word.Document; if (Doc2 != null) { Doc2.Activate(); object start = 0; Range newRang = Doc2.Range(ref start, ref start); int ioo = Doc2.Sections.Count; Section sec = Doc2.Sections[1]; sec.Range.InsertBreak(Type.Missing);//插入换行符 try { //sec.Range.PasteAndFormat(WdRecoveryType.wdPasteDefault); sec.Range.PasteAndFormat(WdRecoveryType.wdFormatOriginalFormatting); mailItem.Save(); ThisAddIn.g_log.Info(string.Format("mailItem doc length is {0}.", Doc2.Content.Text.Length)); if (mailItem.Body == null || mailItem.Body.Length < 100) { Doc2.Activate(); ((_Inspector)(mailItem.GetInspector)).Activate(); ThisAddIn.g_log.Info("mailItem's body is null Or body length is short,Activate over"); } } catch (System.Exception ex) { ThisAddIn.g_log.Info("CopyBody comes Exception: " + ex.ToString()); } } } if (Doc != null) { Marshal.ReleaseComObject(Doc); Doc = null; } if (Doc2 != null) { Marshal.ReleaseComObject(Doc2); Doc2 = null; } ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem exit"); }
private void CopyBody(AppointmentItem ai, MailItem mailItem) { ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem enter"); Word.Document Doc = new Word.Document(); Word.Document Doc2 = new Word.Document(); Word.Application App1; Word.Selection Sel; Doc = ai.GetInspector.WordEditor as Word.Document; Word.Application App2; Word.Selection Sel2; if (Doc != null) { ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length)); Doc.Activate(); Doc.Select(); App1 = Doc.Windows.Application; Sel = App1.Selection; Sel.WholeStory(); Sel.Copy(); Doc2 = mailItem.GetInspector.WordEditor as Word.Document; if (Doc2 != null) { Doc2.Activate(); Doc2.Select(); App2 = Doc2.Windows.Application; Sel2 = App2.Selection; Sel2.WholeStory(); try { Sel2.PasteAndFormat(WdRecoveryType.wdPasteDefault); } catch (System.Exception ex) { ThisAddIn.g_log.Error(string.Format("copy to body exception, {0}", ex.ToString())); } mailItem.Save(); ThisAddIn.g_log.Info(string.Format("mailItem doc length is {0}.", Doc2.Content.Text.Length)); if (mailItem.Body == null || mailItem.Body.Length < 100) { Doc2.Activate(); ((_Inspector)(mailItem.GetInspector)).Activate(); } } } Doc = null; Doc2 = null; App1 = null; App2 = null; Sel = null; Sel2 = null; ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem exit"); }