private void SaveEmail(Outlook.MailItem email, string pad) { pad = AddExtensie(pad); pad = SetPadMetGoedeSlashes(pad); if (File.Exists(pad)) { //Email bestaat al in deze directory FormEmailRename form = new FormEmailRename(); form.SetMelding("De gekozen email komt al voor in deze directory:"); form.SetEmail(pad); form.ShowDialog(); if (form.GetConfirmation() == "Y") { email.SaveAs(form.GetVolledigPad()); } } else { //Bestaat nog niet, save hem maar try { email.SaveAs(pad); } catch (DirectoryNotFoundException) { MessageBox.Show("Het opslaan van de mail op: '" + pad + "' is niet gelukt!", "MailSAVer: Melding", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private void btnSubmit_Click(object sender, EventArgs e) { string strJob = cmbJobNumber.Text.Replace("/", "_").Replace(" ", ""); strJob.Trim(); string path = "R:\\wipviewer2017\\jobfiles\\"; path += strJob + "\\Emails\\"; System.IO.Directory.CreateDirectory(path); path += txtFileName.Text + ".msg"; if (chkAttach.Checked == true) { email.SaveAs(path, outlook.OlSaveAsType.olMSG); MessageBox.Show("Success! Email Exported"); } else { for (int i = 0; i < email.Attachments.Count;) { email.Attachments.Remove(i + 1); i++; } email.SaveAs(path, outlook.OlSaveAsType.olMSG); MessageBox.Show("Success! Email Exported"); } }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { // Create an object of type Outlook.Application Outlook.Application objOutlook = new Outlook.Application(); //Create an object of type olMailItem Outlook.MailItem oIMailItem = objOutlook.CreateItem(Outlook.OlItemType.olMailItem); //Set properties of the message file e.g. subject, body and to address //Set subject oIMailItem.Subject = "This MSG file is created using Office Automation."; //Set to (recipient) address oIMailItem.To = "*****@*****.**"; //Set body of the email message oIMailItem.HTMLBody = "<html><p>This MSG file is created using VBA code.</p>"; //Add attachments to the message oIMailItem.Attachments.Add("image.bmp"); oIMailItem.Attachments.Add("pic.jpeg"); //Save as Outlook MSG file oIMailItem.SaveAs("testvba.msg"); //Open the MSG file oIMailItem.Display(); }
public int createOutputFile(Recepient recepient, String outputDir, String attachmentDirectory) { int createdFiles = 0; try { Outlook.MailItem result = (Outlook.MailItem)mailItem.Copy(); String htmlBody = result.HTMLBody; String pattern = "<span class=SpellE>.*</span>"; String toReplace; foreach (Match m in Regex.Matches(htmlBody, pattern)) { toReplace = m.Value.Replace("<span class=SpellE>", String.Empty).Replace("</span>", String.Empty); htmlBody = htmlBody.Replace(m.Value, toReplace); } String subject = recepient.Subject != null ? recepient.Subject : result.Subject; foreach (string key in recepient.FieldsToReplace.Keys) { string mappedValue = (string)recepient.FieldsToReplace[key]; htmlBody = htmlBody.Replace(key, mappedValue); // result.Subject=result.Subject.Replace(key, (string)recepient.FieldsToReplace[key]); subject = subject.Replace(key, mappedValue); } result.HTMLBody = htmlBody; result.Subject = subject; String resultPath = outputDir + "\\" + recepient.EmployeeID + ".msg"; result.To = recepient.EmailAddress; if (recepient.Cc != null) { result.CC = recepient.Cc; } if (recepient.Bcc != null) { result.BCC = recepient.Bcc; } if (attachmentDirectory != null) { string[] fileArray = Directory.GetFiles(attachmentDirectory); foreach (String filename in fileArray) { if (filename.Contains(recepient.EmployeeID)) { result.Attachments.Add(filename); } } } // if(acc!=null) result.SendUsingAccount = acc; //result.Sender = acc.DisplayName; MailList.Add(result); result.SaveAs(resultPath); createdFiles++; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error creating Excel file for " + recepient.EmployeeID, MessageBoxButtons.OK, MessageBoxIcon.Error); return(createdFiles); } return(createdFiles); }
private void SendViaWeb(string dest, Outlook.MailItem email, string token) { var tmpfilename = Path.GetTempFileName(); var finfo = new FileInfo(tmpfilename); finfo.Attributes = FileAttributes.Temporary; var sb = new StringBuilder(); sb.Append(@"{ 'Event': { 'info': 'Suspicious Email Submitter', 'distribution': 0, 'threat_level_id': 3, 'analysis': 1, 'Object': [ { 'name': 'email', 'meta-category': 'network', 'description': 'Email object describing an email with meta-information', 'template_uuid': 'a0c666e0-fc65-4be8-b48f-3423d788b552', 'template_version': 10, 'Attribute': [ { 'category': 'Payload delivery', 'type': 'attachment', 'object_relation': 'eml', 'value': 'Raw Email', 'data': '"); email.SaveAs(tmpfilename, Outlook.OlSaveAsType.olMSGUnicode); finfo = new FileInfo(tmpfilename); var bytes = new byte[Convert.ToInt32(finfo.Length & 0x7fffffff)]; using (var handle = File.Open(tmpfilename, FileMode.Open)) { handle.Read(bytes, 0, Convert.ToInt32(finfo.Length & 0x7FFFFFFF)); } File.Delete(tmpfilename); sb.Append(Convert.ToBase64String(bytes)); sb.Append(@"' } ] } ] } }"); HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(dest); rq.Headers.Add("Accept:application/json"); rq.Headers.Add("Content-Type:application/json"); rq.Headers.Add("Authorization:" + token); using (var s = new StreamWriter(rq.GetRequestStream())) { s.WriteLine(sb.ToString()); } }
/// <summary> /// Get this attachment of mine as an array of bytes. /// </summary> /// <param name="olItem">Me</param> /// <param name="attachment">The attachment to serialise.</param> /// <returns>An array of bytes representing the attachment.</returns> public static byte[] GetAttachmentAsBytes(this Outlook.MailItem olItem, Outlook.Attachment attachment) { byte[] result = null; Log.Info($"EmailArchiving.GetAttachmentBytes: serialising attachment '{attachment.FileName}' of email '{olItem.Subject}'."); if (attachment != null) { var tempPath = System.IO.Path.GetTempPath(); string uid = Guid.NewGuid().ToString(); var temporaryAttachmentPath = $"{tempPath}\\Attachments_{uid}"; if (!System.IO.Directory.Exists(temporaryAttachmentPath)) { System.IO.Directory.CreateDirectory(temporaryAttachmentPath); } try { var attachmentFilePath = temporaryAttachmentPath + "\\" + attachment.FileName; attachment.SaveAsFile(attachmentFilePath); result = System.IO.File.ReadAllBytes(attachmentFilePath); } catch (COMException ex) { try { Log.Warn("Failed to get attachment bytes for " + attachment.DisplayName, ex); // Swallow exception(!) string strName = temporaryAttachmentPath + "\\" + DateTime.Now.ToString("MMddyyyyHHmmssfff") + ".html"; olItem.SaveAs(strName, Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML); foreach (string strFileName in System.IO.Directory.GetFiles(strName.Replace(".html", "_files"))) { if (strFileName.EndsWith("\\" + attachment.DisplayName)) { result = System.IO.File.ReadAllBytes(strFileName); break; } } } catch (Exception ex1) { Log.Error("EmailArchiving.GetAttachmentBytes", ex1); } } finally { if (System.IO.Directory.Exists(temporaryAttachmentPath)) { System.IO.Directory.Delete(temporaryAttachmentPath, true); } } } return(result); }
public byte[] GetAttachmentBytes(Outlook.Attachment objMailAttachment, Outlook.MailItem objMail) { byte[] strRet = null; Log.Info($"EmailArchiving.GetAttachmentBytes: serialising attachment '{objMailAttachment.FileName}' of email '{objMail.Subject}'."); if (objMailAttachment != null) { var tempPath = System.IO.Path.GetTempPath(); var hash = BitConverter.ToString(((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(new UTF8Encoding().GetBytes(objMail.EntryID))); var temporaryAttachmentPath = $"{tempPath}\\Attachments_{hash}"; if (!System.IO.Directory.Exists(temporaryAttachmentPath)) { System.IO.Directory.CreateDirectory(temporaryAttachmentPath); } try { var attachmentFilePath = temporaryAttachmentPath + "\\" + objMailAttachment.FileName; objMailAttachment.SaveAsFile(attachmentFilePath); strRet = System.IO.File.ReadAllBytes(attachmentFilePath); } catch (COMException ex) { try { Log.Warn("Failed to get attachment bytes for " + objMailAttachment.DisplayName, ex); // Swallow exception(!) string strName = temporaryAttachmentPath + "\\" + DateTime.Now.ToString("MMddyyyyHHmmssfff") + ".html"; objMail.SaveAs(strName, Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML); foreach (string strFileName in System.IO.Directory.GetFiles(strName.Replace(".html", "_files"))) { if (strFileName.EndsWith("\\" + objMailAttachment.DisplayName)) { strRet = System.IO.File.ReadAllBytes(strFileName); break; } } } catch (Exception ex1) { Log.Error("EmailArchiving.GetAttachmentBytes", ex1); } } finally { if (System.IO.Directory.Exists(temporaryAttachmentPath)) { System.IO.Directory.Delete(temporaryAttachmentPath, true); } } } return(strRet); }
public byte[] GetAttachmentBytes(Outlook.Attachment objMailAttachment, Outlook.MailItem objMail) { byte[] strRet = null; Log.Info($"EmailArchiving.GetAttachmentBytes: serialising attachment '{objMailAttachment.FileName}' of email '{objMail.Subject}'."); if (objMailAttachment != null) { var temporaryAttachmentPath = Environment.SpecialFolder.MyDocuments.ToString() + "\\SuiteCRMTempAttachmentPath"; if (!System.IO.Directory.Exists(temporaryAttachmentPath)) { System.IO.Directory.CreateDirectory(temporaryAttachmentPath); } try { var attachmentFilePath = temporaryAttachmentPath + "\\" + objMailAttachment.FileName; objMailAttachment.SaveAsFile(attachmentFilePath); strRet = System.IO.File.ReadAllBytes(attachmentFilePath); } catch (COMException ex) { try { Log.Warn("Failed to get attachment bytes for " + objMailAttachment.DisplayName, ex); // Swallow exception(!) string strName = temporaryAttachmentPath + "\\" + DateTime.Now.ToString("MMddyyyyHHmmssfff") + ".html"; objMail.SaveAs(strName, Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML); foreach (string strFileName in System.IO.Directory.GetFiles(strName.Replace(".html", "_files"))) { if (strFileName.EndsWith("\\" + objMailAttachment.DisplayName)) { strRet = System.IO.File.ReadAllBytes(strFileName); break; } } } catch (Exception ex1) { Log.Error("EmailArchiving.GetAttachmentBytes", ex1); } } finally { if (System.IO.Directory.Exists(temporaryAttachmentPath)) { System.IO.Directory.Delete(temporaryAttachmentPath, true); } } } return(strRet); }
public static string TempSave(Outlook.MailItem email) { try { //blanked in an attempt to handle the weird random saving string folder = ""; folder = XLtools.TempPath(); Random rnd = new Random(); string filename = ""; if (email.Subject == null) { filename = "Email"; } else { filename = email.Subject; } foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { filename = filename.Replace(c.ToString(), ""); } int id = rnd.Next(1000, 9999); //provides a four digit id filename += "-" + id.ToString(); filename += ".msg"; //If that file already exists try again until it doesn't while (File.Exists(folder + filename)) { filename = DateTime.Now.ToString("yyyy-MM-dd"); id = rnd.Next(1000, 9999); //provides a four digit id filename += "-" + id.ToString(); filename += ".msg"; } filename = folder + filename; email.SaveAs(filename); return(filename); } catch (Exception ex) { MessageBox.Show("Unable to save e-mail"); XLtools.LogException("Outlook-TempSave", ex.ToString()); return(null); } }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { string FilePath = @"E:\Aspose\Aspose VS VSTO\Sample Files\ExportEmail.msg"; // Create Application class and get namespace Outlook.Application outlook = new Outlook.Application(); Outlook.NameSpace ns = outlook.GetNamespace("Mapi"); object _missing = Type.Missing; ns.Logon(_missing, _missing, false, true); // Get Inbox information in objec of type MAPIFolder Outlook.MAPIFolder inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); Outlook.MailItem item = inbox.Items[0]; item.SaveAs(FilePath, _missing); }
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); }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { // Creates a new Outlook Application instance Outlook.Application objOutlook = new Outlook.Application(); // Creating a new Outlook message from the Outlook Application instance Outlook.MailItem msgInterop = (Outlook.MailItem)(objOutlook.CreateItem(Outlook.OlItemType.olMailItem)); // Set recipient information msgInterop.To = "*****@*****.**"; msgInterop.CC = "*****@*****.**"; // Set the message subject msgInterop.Subject = "Subject"; // Set some HTML text in the HTML body msgInterop.HTMLBody = "<h3>HTML Heading 3</h3> <u>This is underlined text</u>"; // Save the MSG file in local disk string strMsg = "TestInterop.msg"; msgInterop.SaveAs(strMsg, Outlook.OlSaveAsType.olMSG); }
internal void SlaOpAnders(Outlook.MailItem email) { String pad = GetPad(false); if (pad != null) { //Blijkbaar een \ te weinig,dus pad = pad + @"\"; //Krijg een bestandsnaam volgens wens pad = GetFormattedString(pad, email); //Voeg de extensie er aan toe pad = AddExtensie(pad); //Pas eventuele / aan in \ pad = SetPadMetGoedeSlashes(pad); //Eventuele naamswijzigingen: FormEmailRename form = new FormEmailRename(); if (File.Exists(pad)) { form.SetMelding("Anders opslaan: De gekozen email komt al voor in deze folder:"); } else { form.SetMelding("Anders opslaan: kies eventueel een andere naam:"); } form.SetEmail(pad); form.ShowDialog(); if (form.GetConfirmation() == "Y") { email.SaveAs(form.GetVolledigPad()); } //if (pad != null) //{ // //Sla de mail op // SaveEmail(email, pad); //} } }
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 string ArchiveItem(Outlook.MailItem item, string dir, string newname) { string archived = "erreur"; string shortFilename = String.Format("{0:yyyy-MM-dd_HHmmss}", item.ReceivedTime) + "-"; if (Config.GetInstance().GetOption("ADD_CATEGORIES_IN_FILENAME") == "TRUE") { if (item.Categories != null) { shortFilename += item.Categories.Replace(';', '-') + "-"; } } if (newname != null) { shortFilename += CleanFileName(newname); } else { shortFilename += CleanFileName(item.Subject); } string filename = Path.Combine(dir, shortFilename + ".msg"); // si extraction dans dossier séparé, on redéfini le filename if (extractAttachments) { dir = Path.Combine(dir, shortFilename); filename = Path.Combine(dir, shortFilename + ".msg"); } // si on fleurte avec les limites, on ne sauve pas if (dir.Length > 230) { return(Localisation.getInstance().getString( parent.culture.TwoLetterISOLanguageName, "PATH_TOO_LONG" )); } // si on fleurte avec les limites, on ne sauve pas if (filename.Length > 250) { if (truncatePathTooLong) { filename = filename.Substring(0, 250) + ".msg"; } else if (askPathTooLong) { do { string error = Localisation.getInstance().getString( parent.culture.TwoLetterISOLanguageName, "FULL_PATH_TOO_LONG" ); shortFilename = SingleQuestionForm.Ask( Localisation.getInstance().getString( parent.culture.TwoLetterISOLanguageName, "QUESTION_FULL_PATH_TOO_LONG" ), shortFilename, null, null, error); filename = Path.Combine(dir, shortFilename + ".msg"); } while (filename.Length > 254 || File.Exists(filename)); } else { return(Localisation.getInstance().getString( parent.culture.TwoLetterISOLanguageName, "FULL_PATH_TOO_LONG" )); } } // si fichier déjà existant, on ne sauve pas if (File.Exists(filename)) { return(Localisation.getInstance().getString( parent.culture.TwoLetterISOLanguageName, "FILE_ALREADY_EXISTS" )); } // si extraction des attachements, on est OK sur longueur et not exists, on tente de créer le répertoire if (extractAttachments) { Directory.CreateDirectory(dir); } // on tente de sauver try { item.SaveAs(filename, Outlook.OlSaveAsType.olMSGUnicode); // si extration des attachements, on extract if (extractAttachments) { foreach (Outlook.Attachment att in item.Attachments) { att.SaveAsFile(Path.Combine(dir, att.FileName)); } } archived = "Ok"; } catch (Exception e) { archived = e.Message; } return(archived); }
/// <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); }
private void MailArrival(object Item) { try { LogHelper.Write(LogType.Debug, "Mail Arrived"); Outlook.MailItem item = Item as Outlook.MailItem; if (item != null) { string mailName = ""; if (item.Subject != null) { mailName = MAIL_PATH + item.Subject.Replace(":", "_") + DateTime.Now.ToString("yyyyMMddHHmmss") + ".msg"; } else { mailName = MAIL_PATH + mailName + "NoSubject" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".msg"; } LogHelper.Write(LogType.Debug, "Mail Name: " + mailName); string fileName = ""; try { mailName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".msg"; LogHelper.Write(LogType.Debug, mailName); item.SaveAs(MAIL_PATH + mailName, Outlook.OlSaveAsType.olMSG); } catch (Exception ex) { LogHelper.Write(LogType.Error, "Error Start: Mail Save Error!"); LogHelper.Write(LogType.Error, ex.Message); LogHelper.Write(LogType.Error, item.Subject == null ? string.Empty : item.Subject.ToString()); LogHelper.WriteCase(item.Subject == null ? string.Empty : item.Subject.ToString()); LogHelper.Write(LogType.Error, "End: Mail Save Error"); } int pdfCount = 0; LogHelper.Write(LogType.Debug, "Deal with attachments"); #region Save Attatchments //if (item.Attachments.Count > 0) //{ // foreach (Outlook.Attachment attachment in item.Attachments) // { // string extension = Path.GetExtension(attachment.FileName); // if (extension != ".msg") // { // continue; // } // pdfCount++; // string attachmentName = ATTATCHMENT_PATH + attachment.FileName; // attachment.SaveAsFile(attachmentName); // attachmentName = PDF_FILE_PATH + attachment.FileName; // attachment.SaveAsFile(attachmentName); // fileName += attachment.FileName + "|,|"; // } //} #endregion fileName = SaveAttachment(item,ref pdfCount); LogHelper.Write(LogType.Debug, "Get origindoctype"); //Judge the mail type (转信/返信/他番……) //Emergency Status int originDocType = (int)GetOriginDocType(item.Subject); LogHelper.Write(LogType.Debug, "Get emergency value"); //string caseGuidanceType = SqlHelper.GetCaseGuidanceType(item.Subject); int emergency = GetEmergency(item.Body, item.Subject); if (CompareInfoDate(item.Body)) { if (emergency > 2) emergency = 2; } LogHelper.Write(LogType.Debug, "Get sender address"); string senderAddress = GetSenderAddress(item); LogHelper.Write(LogType.Debug, "Save in database"); //UNDO need to add file type(contract or edc) string receiveTime = item.ReceivedTime == null ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"): item.ReceivedTime.ToString("yyyy-MM-dd HH:mm:ss"); int recordId = SqlHelper.SaveMailRecord(item.EntryID, mailName, fileName, senderAddress, item.Body , originDocType, item.Subject, emergency, pdfCount,receiveTime); LogHelper.Write(LogType.Debug, "Save attachments into pdf folder"); if (originDocType == 0 && item.Attachments.Count > 0) { foreach (Outlook.Attachment att in item.Attachments) { if (Path.GetExtension(att.FileName) == ".pdf") { att.SaveAsFile(PDF_PATH + recordId + "#" + att.FileName); break; //SavePdfFile(att); } } } //else if(originDocType > 0 && item.Attachments.Count > 0) //{ // foreach (Outlook.Attachment it in item.Attachments) // { // if (Path.GetExtension(it.FileName) == ".pdf") // { // SavePdfFile(it); // } // } //} LogHelper.Write(LogType.Debug, "Mail arrive complete"); } } catch (Exception ex) { Outlook.MailItem item = Item as Outlook.MailItem; if (item != null && item.Subject != null) { LogHelper.WriteCase(item.Subject); } LogHelper.Write(LogType.Error, ex.Message); LogHelper.Write(ex); } }
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 void Save(bool skipSaveSuccessDialog = false) { var isNewMode = (tabControl1.SelectedTab == tabNewItem); var isUpdateMode = (tabControl1.SelectedTab == tabUpdateItem); btnSaveNClose.Enabled = false; btnSave.Enabled = false; List <string> saveFilePaths = new List <string>(); string tempFolder = GetTempFolder(); try { Directory.CreateDirectory(tempFolder); var tfsConnection = Globals.ThisAddIn.Settings.TfsConfigurations[cbProject.SelectedIndex]; WorkItemTrackingHttpClient witClient = GetVssClient(tfsConnection); WorkItem result = null; var bodyText = new StringBuilder(txtBody.Text); if (isNewMode) { JsonPatchDocument patchDocument = new JsonPatchDocument(); //add fields and their values to your patch document patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = txtTitle.Text } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/Microsoft.VSTS.TCM.ReproSteps", Value = bodyText.ToString() } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Description", Value = bodyText.ToString() } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/Microsoft.VSTS.TCM.SystemInfo", Value = txtSystemInformation.Text } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/Microsoft.VSTS.Common.Priority", Value = cbPriority.Text } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/Microsoft.VSTS.Common.Severity", Value = cbSeverity.Text } ); //TODO: //patchDocument.Add( // new JsonPatchOperation() // { // Operation = Operation.Add, // Path = "/fields/System.AssignedTo", // Value = _exchangeUser.Name + " <" + _exchangeUser.PrimarySmtpAddress + ">" // } //); // add parent if (parentItem != null) { patchDocument.Add(new Microsoft.VisualStudio.Services.WebApi.Patch.Json.JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "System.LinkTypes.Hierarchy-Reverse", url = tfsConnection.TfsUrl + tfsConnection.TfsProject + "/_apis/wit/workItems/" + parentItem.Id, attributes = new { comment = "link parent WIT" } } }); var fieldsToInherit = new string[] { "System.AreaPath", "System.IterationPath" }; foreach (var fieldToInherit in fieldsToInherit) { if (parentItem.Fields.ContainsKey(fieldToInherit)) { patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/" + fieldToInherit, Value = parentItem.Fields[fieldToInherit] } );; } } } /* * patchDocument.Add( * new JsonPatchOperation() * { * Operation = Operation.Add, * Path = "/fields/Microsoft.VSTS.Common.ReviewedBy", * Value = _outlookCurrentMailItem.SenderName + " <" + _outlookCurrentMailItem.Sender.GetExchangeUser().PrimarySmtpAddress + ">" * } * ); */ result = witClient.CreateWorkItemAsync(patchDocument, tfsConnection.TfsProject, cbWorkItemType.Text).Result; } else { result = existingItem; } // test //https://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/WorkItemTracking/WorkItemsSample.cs //var commentsDocument = new JsonPatchDocument(); //commentsDocument.Add( // new JsonPatchOperation() // { // Operation = Operation.Add, // Path = "/fields/System.History", // Value = "test comment from client lib sample code", // } //); //WorkItem commentsREsult = witClient.UpdateWorkItemAsync(commentsDocument, result.Id.Value).Result; //var q = 1; //// add files if (chkLstBoxAttachements.GetItemChecked(0)) { var subject = _outlookCurrentMailItem.Subject.GetSafeFileSystemName() + ".msg"; string allMessage = tempFolder + subject; saveFilePaths.Add(allMessage); _outlookCurrentMailItem.SaveAs(allMessage, OlSaveAsType.olMSG); } // this is not a mistake, the first checkbox is reserved for the whole message, // and the outlook attachments weirdly is numbered from 1 for (int i = 1; i < chkLstBoxAttachements.Items.Count; i++) { if (chkLstBoxAttachements.GetItemChecked(i)) { var filename = _outlookCurrentMailItem.Attachments[i].GetFileName(); filename = filename.GetSafeFileSystemName(); string fPath = tempFolder + filename; saveFilePaths.Add(fPath); _outlookCurrentMailItem.Attachments[i].SaveAsFile(fPath); } } if ((saveFilePaths.Count > 0) || (isUpdateMode)) { List <string> uploadedAttachementUrl = new List <string>(); if (saveFilePaths.Count > 0) { JsonPatchDocument attachDocument = new JsonPatchDocument(); foreach (string fp in saveFilePaths) { AttachmentReference attachment = null; Task taskAttach = new Task(() => { attachment = witClient.CreateAttachmentAsync(fp).Result; }); taskAttach.Start(); Task.WaitAll(new[] { taskAttach }); attachDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "AttachedFile", url = attachment.Url, attributes = new { name = Path.GetFileName(fp), comment = txtAttachementComment.Text } } } );; uploadedAttachementUrl.Add(attachment.Url); } WorkItem attachmentResult = witClient.UpdateWorkItemAsync(attachDocument, result.Id.Value).Result; } //Prepare new body text bodyText.Append("<br/>"); foreach (string ustr in uploadedAttachementUrl) { var extension = System.IO.Path.GetExtension(ustr).ToLower(); if (imageExtensions.Contains(extension)) { bodyText.Append("<br/>"); bodyText.Append(String.Format("<img src =\"{0}\"/> ", ustr)); } } if (isNewMode) { JsonPatchDocument updatedItemBody = new JsonPatchDocument(); updatedItemBody.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/Microsoft.VSTS.TCM.ReproSteps", Value = bodyText.ToString() } ); updatedItemBody.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Description", Value = bodyText.ToString() } ); WorkItem finalResult = witClient.UpdateWorkItemAsync(updatedItemBody, result.Id.Value).Result; var url = GetUrlFromWorkItem(finalResult); System.Windows.Forms.Clipboard.SetText(url, TextDataFormat.Text); MessageBox.Show("Item Created Successfully, with ID: " + finalResult.Id + "\r\n\r\n" + url, "Item Created With Attachment, URL copied to clipboard"); } else if (isUpdateMode) { JsonPatchDocument updatedItemBody = new JsonPatchDocument(); updatedItemBody.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.History", Value = bodyText.ToString() } ); WorkItem finalResult = witClient.UpdateWorkItemAsync(updatedItemBody, result.Id.Value).Result; var url = GetUrlFromWorkItem(finalResult); System.Windows.Forms.Clipboard.SetText(url, TextDataFormat.Text); if (!skipSaveSuccessDialog) { MessageBox.Show("Item updated Successfully, with ID: " + finalResult.Id + "\r\n\r\n" + url, "Item Updated, URL copied to clipboard"); } } } else { var url = GetUrlFromWorkItem(result); System.Windows.Forms.Clipboard.SetText(url, TextDataFormat.Text); if (!skipSaveSuccessDialog) { MessageBox.Show("Item Created Successfully, with ID: " + result.Id + "\r\n\r\n" + url, "Item Created, URL copied to clipboard"); } } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } finally { try { foreach (string fp in saveFilePaths) { if (File.Exists(fp)) { File.Delete(fp); } } } catch (System.Exception ex) { //TODO: silently log? } CheckAndEnableControls(); } }
/// <summary> /// 将邮件保存到公共盘 /// </summary> /// <param name="myItem">要保存的邮件</param> /// <param name="mailSaveNameFilePath">保存邮件的完整路径</param> private void SaveMailItemToDisk(Outlook.MailItem myItem, string mailSaveNameFilePath) { myItem.SaveAs(mailSaveNameFilePath); }
private static void ThisMai_send(ref bool Cancel) { if (bestellliste != null) { using (DAL.PrintumProjekteEntities db = new DAL.PrintumProjekteEntities()) { try { string bestellIdText = bestellliste[0].BestellnungIDTest; DAL.Bestellungen bestellungen = (from p in db.Bestellungen where p.BestellungIDText == bestellIdText select p) .First(); if (bestellungen != null) { bestellungen.geaendert = DateTime.Now; bestellungen.GeaendertVon = Environment.UserName; bestellungen.istAbgeschickt = true; bestellungen.PDFpfad = pdfPfad; } foreach (var item in bestellliste) { DAL.BestellungPositionen bestellungPositionen = new DAL.BestellungPositionen(); bestellungPositionen.Artikelbezeichnung = item.Artikelbezeichnung; bestellungPositionen.BestellnungIDTest = item.BestellnungIDTest; bestellungPositionen.Einzelpreis = item.Einzelpreis; bestellungPositionen.Gesammtpreis = item.Gesammtpreis; bestellungPositionen.Liefertermin = item.Liefertermin; bestellungPositionen.Pos = item.Pos; bestellungPositionen.Projektnummer = projektnr; bestellungPositionen.Stueck = item.Stueck; bestellungPositionen.Besteller = Environment.UserName; bestellungPositionen.Bestelldatum = DateTime.Now; db.BestellungPositionen.Add(bestellungPositionen); } db.SaveChanges(); dieMail.SaveAs(mailPfad); (Application.OpenForms["Form1_main"] as Form1_main).BestellungenNeuLaden(); } catch (Exception ex) { Helper.LogHelper.WriteDebugLog(ex.ToString()); } finally { if ((Application.OpenForms["Form1_main"] as Form1_main) .Controls["button4_mail"] != null) { (Application.OpenForms["Form1_main"] as Form1_main) .Controls["button4_mail"].Enabled = true; } } } } }
public async Task <bool> UploadEmail(Outlook.MailItem item, string nodeId, int?count) { try { string name = item.Subject; List <char> invalidFileNameChars = Path.GetInvalidFileNameChars().ToList(); invalidFileNameChars.AddRange(Path.GetInvalidPathChars()); var filename = new string(name.Select(ch => invalidFileNameChars.Contains(ch) ? Convert.ToChar(invalidFileNameChars.IndexOf(ch) + 65) : ch).ToArray()); if (filename.Length > 200) { filename = filename.Substring(0, 200); } filename = filename.Replace(".", ""); // Create Folder Nodes node = new Nodes(); string alt = filename + "_" + (count + 1); string folderId = await node.CreateFolder(nodeId, filename, alt); if (string.IsNullOrEmpty(folderId)) { Error = node.Error; return(false); } if (node.UseAlternative) { filename = alt; } // Save Email string messagePath = Option.TempFolder + filename + ".msg"; item.SaveAs(messagePath, Outlook.OlSaveAsType.olMSGUnicode); //Save Attachment List <string> AttachmentList = new List <string>(); foreach (Outlook.Attachment attachment in item.Attachments) { if (attachment.Type != Outlook.OlAttachmentType.olByValue) { continue; } var attachMethod = 0; var attachFlags = 0; string PR_ATTACH_METHOD = "http://schemas.microsoft.com/mapi/proptag/0x37050003"; try { attachMethod = attachment.PropertyAccessor.GetProperty(PR_ATTACH_METHOD); } catch (Exception ex) { // skip } string PR_ATTACH_FLAGS = "http://schemas.microsoft.com/mapi/proptag/0x37140003"; try { attachFlags = attachment.PropertyAccessor.GetProperty(PR_ATTACH_FLAGS); } catch (Exception ex) { // skip } if (item.BodyFormat == Outlook.OlBodyFormat.olFormatHTML) { if (attachFlags == 4) { continue; } } if (item.BodyFormat == Outlook.OlBodyFormat.olFormatRichText) { if (attachMethod == 6) { continue; } } if (item.HTMLBody.Contains("cid:" + attachment.FileName)) { continue; } string path = Option.TempFolder + attachment.FileName; if (path.Length > 245) { path = path.Substring(0, 240) + ".." + Path.GetExtension(attachment.FileName); } attachment.SaveAsFile(path); AttachmentList.Add(path); Marshal.ReleaseComObject(attachment); } // Upload File UploadFile uFile = new UploadFile(); bool isUploaded = await uFile.Upload(folderId, messagePath); Error = uFile.Error; if (isUploaded) { foreach (string attchPath in AttachmentList) { isUploaded = await uFile.Upload(folderId, attchPath); Error = uFile.Error; } } AttachmentList.Add(messagePath); DeleteFolders(AttachmentList); return(isUploaded); } finally { } }
public string GetOneMail(string EmailAddress, string Profile, string LogPath, string LogData, string FolderName, string EmailType, string AttachmentSavePath = "", string RetainOriginalAttName = "true", string EmailSavePath = "", string EmailExtension = "", string MarkAsRead = "", string MoveEmailToFolder = "") { string results = ""; try { Outlook.Items folderItems = null; Outlook.MailItem foundMail = null; object foundItem = null; Connection conn = null; NameSpace nameSpace = null; string log = ""; Outlook.Folder outboxFolder = null; Outlook.MAPIFolder oFolder; log = "Creating new connection to Outlook"; conn = new Connection(); Outlook.Application application = conn.InitializeConnection(EmailAddress, Profile, out nameSpace, out outboxFolder, out oFolder); MAPIFolder subFolder = null; if (FolderName.ToLower() == "inbox") { subFolder = oFolder; } else { foreach (MAPIFolder folder in oFolder.Folders) { if (folder.Name == FolderName) { subFolder = folder; break; } } } //Console.WriteLine(subFolder.UnReadItemCount.ToString() ); log = "Connected to folder " + subFolder.Name; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); if (subFolder.DefaultItemType == Outlook.OlItemType.olMailItem) { folderItems = subFolder.Items; //Creating filter for unread/read or all if (EmailType.ToLower() == "unread") { foundItem = folderItems.Find("[Unread]=true"); //Console.WriteLine(subFolder.UnReadItemCount.ToString() ); log = "Obtaining only UNREAD emails. Total found: " + subFolder.UnReadItemCount.ToString(); } else if (EmailType.ToLower() == "read") { foundItem = folderItems.Find("[Unread]=false"); log = "Obtaining only READ emails"; } else if (EmailType.ToLower() == "all") { foundItem = (Outlook.MailItem)subFolder.Items.GetFirst(); log = "Obtaining ALL emails"; } else { return("Incorrect filter. Allowed only: read/unread/all"); } string SenderEmailAddress = ""; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); while (foundItem != null) { try { if (foundItem is Outlook.MailItem) { foundMail = foundItem as Outlook.MailItem; if (foundMail.Sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || foundMail.Sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { Outlook.ExchangeUser exchUser = foundMail.Sender.GetExchangeUser(); if (exchUser != null) { SenderEmailAddress = exchUser.PrimarySmtpAddress; } } else { SenderEmailAddress = foundMail.SenderEmailAddress.ToString(); } log = "Found email - Subject: " + foundMail.Subject + " From: " + foundMail.SenderEmailAddress.ToString() + " Received date: " + foundMail.ReceivedTime.ToString(); File.AppendAllText(LogPath, LogData + log + Environment.NewLine); if (AttachmentSavePath != "") { int fileID = 0; log = "Attachment saving requested"; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); foreach (Attachment attachment in foundMail.Attachments) { int strCID = (int)attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003"); if (strCID != 0) { continue; } if (RetainOriginalAttName.ToLower() == "false") { fileID++; string extension = Path.GetExtension(attachment.FileName); log = "Saving: " + AttachmentSavePath + attachment.FileName; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); attachment.SaveAsFile(AttachmentSavePath + fileID + extension); } else { log = "Saving: " + AttachmentSavePath + attachment.FileName; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); attachment.SaveAsFile(AttachmentSavePath + attachment.FileName); } } } if (EmailSavePath != "") { log = "Email saving requested"; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); Regex rgx = new Regex("[^a-zA-Z0-9 ]"); string emailfilename = rgx.Replace(foundMail.Subject.ToString(), ""); log = "Email name changed to: " + emailfilename; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); if (EmailExtension != "") { if (EmailExtension.ToLower() == "mht") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olMHTML); } else if (EmailExtension.ToLower() == "msg") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olMSG); } else if (EmailExtension.ToLower() == "html") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olHTML); } else if (EmailExtension.ToLower() == "txt") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olTXT); } else if (EmailExtension.ToLower() == "rtd") { foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olRTF); } //foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension); log = "Saving email: " + EmailSavePath + emailfilename + "." + EmailExtension; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); } else { log = "Saving email: " + EmailSavePath + emailfilename + ".msg"; File.AppendAllText(LogPath, LogData + log + Environment.NewLine); foundMail.SaveAs(EmailSavePath + emailfilename + ".msg"); } } if (MarkAsRead.ToLower() == "true") { foundMail.UnRead = false; foundMail.Save(); } if (MoveEmailToFolder != "") { foreach (MAPIFolder folder in oFolder.Folders) { if (folder.Name == MoveEmailToFolder) { foundMail.Move(folder); } } } } else { if (foundItem != null) { Marshal.ReleaseComObject(foundItem); } foundItem = folderItems.FindNext(); continue; } try { //results = SenderEmailAddress.ToString() + "|#|" + foundMail.Subject.ToString() + "|#|" + foundMail.ReceivedTime.ToString(); results = foundMail.SenderEmailAddress.ToString() + "|#|" + foundMail.Subject + "|#|" + foundMail.ReceivedTime.ToString(); } catch (System.Exception) { } if (foundItem != null) { Marshal.ReleaseComObject(foundItem); } } catch (System.Exception) { } // //Console.WriteLine(foundItem.ToString()); break; } } else { foundItem = folderItems.FindNext(); } if (results == "") { return("No emails for processing"); } return(results); } catch (System.Exception ex) { return("Failed: " + ex.ToString()); } }
private void emailerFunction(int lineNum) { int i; for (i = 0; i < lineNum + 1; i++) { Outlook.MailItem oMsg = m_Item.Application.CreateItem(Outlook.OlItemType.olMailItem); oMsg.Subject = olMsgArray[i, 0]; Outlook.Recipients oRecips = oMsg.Recipients; Outlook.Recipient oRecipTo = oRecips.Add(olMsgArray[i, 4]); oRecipTo.Type = (int)Outlook.OlMailRecipientType.olTo; oRecipTo.Resolve(); // saving email in client folder, doing this on send is more complicated string corrsDir = olMsgArray[i, 6] + @"\6. CST\Docs Control\Corrs\"; if (!System.IO.Directory.Exists(corrsDir)) { System.IO.Directory.CreateDirectory(corrsDir); } DateTime stdDT = DateTime.Now; string dtFormat = "yyMMdd HHmm"; oMsg.SaveAs(corrsDir + olMsgArray[i, 7] + " " + stdDT.ToString(dtFormat) + " EOAH,msg"); if (olMsgArray[i, 5] == "false") { oMsg.HTMLBody = olMsgArray[i, 1] + olMsgArray[i, 2] + olMsgArray[i, 3] + mSignature; // to resolve ambiguity between method 'Microsoft.Office.Interop.Outlook._MailItem.Send()' // and non-method 'Microsoft.Office.Interop.Outlook.ItemEvents_10_Event.Send'. Using method group. ((Outlook._MailItem)oMsg).Send(); } // if the chkNoLink check box is checked then we are opening a compose email form so that the user can custom add the attachments // its too complicated to programmatically attach the attachments else if (olMsgArray[i, 5] == "true") { oMsg.HTMLBody = "<HTML><HEAD></HEAD><BODY>Dear " + ahName + "<p>We have received the following document/s (Copies attached for your ready reference):</p>" + "<p><ul>" + olMsgArray[i, 2] + olMsgArray[i, 3] + mSignature; oMsg.Display(false); } // code below to add CCs //Outlook.Recipient oRecipCC = oRecips.Add("add CC email here"); //oRecipCC.Type = (int)Outlook.OlMailRecipientType.olCC; //oRecipCC.Resolve(); //oMsg.Display(false); // to resolve ambiguity between method 'Microsoft.Office.Interop.Outlook._MailItem.Send()' // and non-method 'Microsoft.Office.Interop.Outlook.ItemEvents_10_Event.Send'. Using method group. //((Outlook._MailItem)oMsg).Send(); oMsg = null; oRecipTo = null; oRecips = null; //oRecipCC = null; } // below code will delete the elements from the array that have already been used to send an email and also // move all other elements up one line; for (i = 0; i < olMsgArray.GetUpperBound(0) + 1; i++) { int x; for (x = 0; x < olMsgArray.GetUpperBound(1) + 1; x++) { try { olMsgArray[i, x] = olMsgArray[i + 1, x]; } catch { break; } } } // make sure to put empty strings in the element lines that have been moved up for (i = 0; i < lineNum + 1; i++) { int x; for (x = 0; x < olMsgArray.GetUpperBound(1) + 1; x++) { // if numlines is 0 then only the last line would be empty //MessageBox.Show(olMsgArray[olMsgArray.GetUpperBound(0) - i, x]); olMsgArray[olMsgArray.GetUpperBound(0) - i, x] = ""; } } }
public StagingTicket invoke(Outlook.MailItem mail) { StagingTicket ticket = new StagingTicket(); //Calling CreateSOAPWebRequest method HttpWebRequest request = CreateSOAPWebRequest(); XmlDocument SOAPReqBody = new XmlDocument(); //declare SOAP message builder StringBuilder soap = new StringBuilder(); //create envelope soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:Outlook2Remedy\">\n"); //create auth header soap.Append("\t<soapenv:Header>\n" + "\t\t<urn:AuthenticationInfo>\n" + "\t\t\t<urn:userName>" + Properties.Settings.Default.RemedyUsername + "</urn:userName>\n" + "\t\t\t<urn:password>" + Properties.Settings.Default.RemedyPassword + "</urn:password>\n" + "\t\t</urn:AuthenticationInfo>\n" + "\t</soapenv:Header>\n"); //open Body and start creating event soap.Append("\t<soapenv:Body>\n" + "\t\t<urn:Create>\n"); //add workflow variables soap.Append("\t\t\t<urn:Submitter>" + Environment.UserName.ToLower() + "</urn:Submitter>\n" + "\t\t\t<urn:EventCode>" + Properties.Settings.Default.EventCode + "</urn:EventCode>\n"); //add email content (subject and body) soap.Append("\t\t\t<urn:EmailSubject>" + (mail.Subject != null ? WebUtility.HtmlEncode(mail.Subject) : "(no subject)") + "</urn:EmailSubject>\n" + "\t\t\t<urn:EmailBody>" + WebUtility.HtmlEncode(mail.Body) + "</urn:EmailBody>\n"); //add attachment details if(Properties.Settings.Default.EmailAttachment) { string path = AppDomain.CurrentDomain.BaseDirectory + @"\temp"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); if (mail.Subject.Length > 50) path += @"\"+ HandleSpecialChars(mail.Subject.Substring(0, 49), "_") + ".msg"; else path += @"\" + HandleSpecialChars(mail.Subject, "_") + ".msg"; mail.SaveAs(path, Outlook.OlSaveAsType.olMSG); soap.Append("<urn:EML_attachmentName>" + path + "</urn:EML_attachmentName>"); soap.Append("<urn:EML_attachmentData>" + Convert.ToBase64String(GetEmailContent(path)) + "</urn:EML_attachmentData>"); soap.Append("<urn:EML_attachmentOrigSize>" + GetEmailLength(path) + "</urn:EML_attachmentOrigSize>"); File.Delete(path); } //add releated ticket - if is found soap.Append("\t\t\t<urn:RelatedTicketID>" + GetTicketReference(mail.Subject) + "</urn:RelatedTicketID>\n"); //add recepients soap.Append("\t\t\t<urn:EmailFrom>" + WebUtility.HtmlEncode(mail.SenderEmailAddress) + "</urn:EmailFrom>\n" + "\t\t\t<urn:EmailTO>" + WebUtility.HtmlEncode(mail.To) + "</urn:EmailTO>\n" + "\t\t\t<urn:EmailCC>" + WebUtility.HtmlEncode(mail.CC) + "</urn:EmailCC>\n"); //closing event, Body and envelope soap.Append("\t\t</urn:Create>\n" + "\t</soapenv:Body>\n" + "</soapenv:Envelope>"); //prepare XML SOAP request SOAPReqBody.LoadXml(soap.ToString()); //send XML SOAP request to server using (Stream stream = request.GetRequestStream()) { SOAPReqBody.Save(stream); } //Geting response from request using (WebResponse Serviceres = request.GetResponse()) { using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream())) { //reading stream var strResponse = rd.ReadToEnd(); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(strResponse); XmlNamespaceManager nsm = new XmlNamespaceManager(xmldoc.NameTable); nsm.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/"); nsm.AddNamespace("ns0", "urn:Outlook2Remedy"); XmlNode node1 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:RID", nsm); if (node1 != null && node1.InnerText != null) ticket.rid = node1.InnerText; else ticket.rid = null; XmlNode node2 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:WID", nsm); if (node2 != null && node2.InnerText != null) ticket.wid = node2.InnerText; else ticket.wid = null; XmlNode node3 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:STS", nsm); if (node3 != null && node3.InnerText != null) ticket.sts = node3.InnerText; else ticket.sts = "open"; XmlNode node4 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:LOG", nsm); if (node4 != null && node4.InnerText != null) ticket.log = node4.InnerText; else ticket.log = null; } } return ticket; }
private void ItemSend_BeforeSend(object item, ref bool cancel) { string ticketID; string filePath; string fileName; string subject; Regex regex; Match match; cancel = false; Outlook.MailItem mailItem = item as Outlook.MailItem; if (mailItem == null) { return; } #region build regex try { regex = new Regex(global::SAPOutlookAddIn.Properties.Settings.Default.SubjectPattern); } catch (Exception ex) { return; } #endregion #region extract TicketID ticketID = null; match = regex.Match(mailItem.Subject); if (!match.Success) { return; } ticketID = match.Groups["TicketID"].Value; #endregion #region create destination folder filePath = Path.Combine(global::SAPOutlookAddIn.Properties.Settings.Default.SavePath, ticketID); try { Directory.CreateDirectory(filePath); } catch (Exception ex) { return; } #endregion #region remove invalid chars from subject subject = mailItem.Subject; foreach (char invalidChar in Path.GetInvalidFileNameChars()) { subject = subject.Replace(invalidChar, ' '); } #endregion #region save email fileName = Path.Combine(filePath, $"{subject}.msg"); try { mailItem.SaveAs(fileName); } catch (Exception ex) { return; } #endregion }
private void ImagePanel_Drop(object sender, DragEventArgs e) { string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false); if (FileList == null) { Outlook.Application outlook = new Outlook.Application(); Outlook.Explorer oExplorer = outlook.ActiveExplorer(); Outlook.Selection oSelection = oExplorer.Selection; string baseProjDir = System.IO.Path.Combine("C:\\Project_Notes\\Stored_Content", this.ProjectID.ToString()); if (!Directory.Exists(baseProjDir)) { Directory.CreateDirectory(baseProjDir); } foreach (object item in oSelection) { Outlook.MailItem mi = (Outlook.MailItem)item; string filePath = System.IO.Path.Combine(baseProjDir, mi.Subject); using ( SqlConnection conn = new SqlConnection( "Server=(LocalDB)\\MSSQLLocalDB;Database=Project_Notes;Integrated Security = true")) { conn.Open(); //insert log, the creation_date is added by default string sql = @" INSERT INTO FILES(filepath,Project_ID) VALUES(@filepath,@projectId); "; using (SqlCommand cmd = new SqlCommand(sql, conn)) { string cd = mi.CreationTime.ToString("MM-dd-yy HH:mm"); string inside = mi.Subject + " (" + cd + ").msg"; inside = inside.Replace("/", "").Replace(":", "-"); string saveString = System.IO.Path.Combine(baseProjDir, inside); cmd.Parameters.Add("@filepath", saveString); cmd.Parameters.Add("@projectId", this.ProjectID); mi.SaveAs(saveString, Outlook.OlSaveAsType.olMSG); mi.Save(); if (File.Exists(saveString)) { cmd.ExecuteNonQuery(); } else { MessageBox.Show("Failed to save email"); } } } } } else if (FileList[0] != null) { string baseProjDir = System.IO.Path.Combine("C:\\Project_Notes\\Stored_Content", this.ProjectID.ToString()); if (!Directory.Exists(baseProjDir)) { Directory.CreateDirectory(baseProjDir); } foreach (var file in FileList) { string filePath = System.IO.Path.Combine(baseProjDir, System.IO.Path.GetFileName(file.ToString()).Replace("/", "").Replace(":", "")); using ( SqlConnection conn = new SqlConnection( "Server=(LocalDB)\\MSSQLLocalDB;Database=Project_Notes;Integrated Security = true")) { conn.Open(); //insert log, the creation_date is added by default string sql = @" INSERT INTO FILES(filepath,Project_ID) VALUES(@filepath,@projectId); "; using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add("@filepath", filePath); cmd.Parameters.Add("@projectId", this.ProjectID); File.Copy(file, filePath, overwrite: true); cmd.ExecuteNonQuery(); } } } } Files fileWindow = new Files(this.ProjectID, this.ArchivedMode); App.Current.MainWindow = fileWindow; this.Close(); fileWindow.Show(); }
public void saveMailItem(string projectnumber) { string[] dirs = { "" }; if (mailItem == null) { return; } try { if (System.IO.Directory.Exists(network_path)) { //finds the project dir where path ends with "*project" //dirs = Directory.GetDirectories(network_path, "*" + project, System.IO.SearchOption.AllDirectories); //Note: // .../dir1/asdproject and .../dir1/project are also found!! mailItem.SaveAs(nameBuilder(projectnumber, mailItem.Subject, dateBuilder(mailItem.SentOn), dateBuilder(DateTime.Now))); //mailItem.SaveAs(dirs[0] + "\\" + nameBuilder(project, mailItem.Subject) + ".msg"); //mailItem.Categories = "Iktatva"; try { var customCat = "Iktatásra küldve"; if (Application.Session.Categories[customCat] == null) { Application.Session.Categories.Add(customCat, Outlook.OlCategoryColor.olCategoryColorDarkRed); } mailItem.Categories = customCat; //mailItem.MarkAsTask(Outlook.OlMarkInterval.olMarkNoDate); } catch (Exception ex) { MessageBox.Show("Sikertelen kategorizálás", "Sikertelen kategorizálás!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } MessageBox.Show("Sikeres hálózati mentés", "Sikeresen elküldve iktatásra!", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { //save file to local buffer if (!Directory.Exists(local_path)) { DirectoryInfo di = Directory.CreateDirectory(local_path); di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; } mailItem.SaveAs(nameBuilder(projectnumber, mailItem.Subject, dateBuilder(mailItem.SentOn), dateBuilder(DateTime.Now))); mailItem.MarkAsTask(Outlook.OlMarkInterval.olMarkNoDate); MessageBox.Show("Sikertelen hálózati mentés", "Sikertelen iktatásra küldés!", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Sikeres lokális mentés", "Sikeresen elküldve iktatásra!", MessageBoxButtons.OK, MessageBoxIcon.Information); } (mailItem as Microsoft.Office.Interop.Outlook._MailItem).Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olSave); } catch (UnauthorizedAccessException ex) { // MessageBox.Show("UnauthorizedAccessException\n", "Sikertelen iktatásra küldés!\n", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (DirectoryNotFoundException ex) { // MessageBox.Show("DirectoryNotFoundException\n", "Sikertelen iktatásra küldés!\n", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { // MessageBox.Show("Exception\n" + ex.ToString(), "Sikertelen iktatásra küldés!\n", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private async void buttonArchive_Click(object sender, EventArgs e) { if (validateData()) { //this.Enabled = false; #region Save email System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly(); Uri asseblyLocation = new Uri(assemblyInfo.Location); string location = Path.GetDirectoryName(asseblyLocation.LocalPath.ToString()); Outlook.Inspector activeInspector = Globals.ThisAddIn.Application.ActiveInspector(); Outlook.MailItem mailItem = (Outlook.MailItem)activeInspector.CurrentItem; string fileName = mailItem.Subject; List <char> invalidChars = new List <char>(Path.GetInvalidFileNameChars()); // adding extra characters to be substituted invalidChars.Add('&'); foreach (char invalidChar in invalidChars) { fileName = fileName.Replace(invalidChar, '_'); } fileName += ".msg"; mailItem.SaveAs(location + "\\" + fileName); #endregion #region Convert email to base64 string string base64; using (FileStream reader = new FileStream(location + "\\" + fileName, FileMode.Open)) { byte[] buffer = new byte[reader.Length]; reader.Read(buffer, 0, (int)reader.Length); base64 = Convert.ToBase64String(buffer); } #endregion #region Upload document if (verifyCredential()) { // Create Item string documentTypeName = ((KeyValuePair <string, string>)comboBoxDocumentType.SelectedItem).Key; ItemCreate itemCreate = getItemToUpload(documentTypeName, base64, fileName); //DocumentTypeManager.Instance.CreateItem(itemCreate).GetAwaiter(); MessageBox.Show("Document is being archived...", "IDM Tools - Victaulic", MessageBoxButtons.OK, MessageBoxIcon.Information); await Task.Run(() => DocumentTypeManager.Instance.CreateItem(itemCreate)); if (DocumentTypeManager.CreateItemAPICallStatus == HttpStatusCode.OK) { MessageBox.Show("Document successfuly archived!", "IDM Tools - Victaulic", MessageBoxButtons.OK, MessageBoxIcon.Information); logger.Log("Item " + fileName + " has been successfully added!"); } else { MessageBox.Show("Document was not archived. Reason: " + DocumentTypeManager.CreateItemAPICallStatus.ToString(), "IDM Tools - Victaulic", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(DocumentTypeManager.CreateItemAPICallResponceError.message); logger.Log(DocumentTypeManager.CreateItemAPICallResponceError.code + ":" + DocumentTypeManager.CreateItemAPICallResponceError.message); logger.Log(DocumentTypeManager.CreateItemAPICallResponceError.detail); } } #endregion } }
public byte[] Base64Encode(Outlook.Attachment objMailAttachment, Outlook.MailItem objMail) { byte[] strRet = null; if (objMailAttachment != null) { if (System.IO.Directory.Exists(Environment.SpecialFolder.MyDocuments.ToString() + "\\SuiteCRMTempAttachmentPath") == false) { string strPath = Environment.SpecialFolder.MyDocuments.ToString() + "\\SuiteCRMTempAttachmentPath"; System.IO.Directory.CreateDirectory(strPath); } try { objMailAttachment.SaveAsFile(Environment.SpecialFolder.MyDocuments.ToString() + "\\SuiteCRMTempAttachmentPath\\" + objMailAttachment.FileName); strRet = System.IO.File.ReadAllBytes(Environment.SpecialFolder.MyDocuments.ToString() + "\\SuiteCRMTempAttachmentPath\\" + objMailAttachment.FileName); } catch (COMException ex) { try { string strLog; strLog = "------------------" + System.DateTime.Now.ToString() + "-----------------\n"; strLog += "AddInModule.Base64Encode method COM 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 += "Inputs:" + "\n"; strLog += "Data:" + objMailAttachment.DisplayName + "\n"; strLog += "-------------------------------------------------------------------------" + "\n"; clsSuiteCRMHelper.WriteLog(strLog); ex.Data.Clear(); string strName = Environment.SpecialFolder.MyDocuments.ToString() + "\\SuiteCRMTempAttachmentPath\\" + DateTime.Now.ToString("MMddyyyyHHmmssfff") + ".html"; objMail.SaveAs(strName, Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML); foreach (string strFileName in System.IO.Directory.GetFiles(strName.Replace(".html", "_files"))) { if (strFileName.EndsWith("\\" + objMailAttachment.DisplayName)) { strRet = System.IO.File.ReadAllBytes(strFileName); break; } } } catch (Exception ex1) { string strLog; strLog = "------------------" + System.DateTime.Now.ToString() + "-----------------\n"; strLog += "AddInModule.Base64Encode method 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 += "Inputs:" + "\n"; strLog += "Data:" + objMailAttachment.DisplayName + "\n"; strLog += "-------------------------------------------------------------------------" + "\n"; clsSuiteCRMHelper.WriteLog(strLog); ex1.Data.Clear(); } } finally { if (System.IO.Directory.Exists(Environment.SpecialFolder.MyDocuments.ToString() + "\\SuiteCRMTempAttachmentPath") == true) { System.IO.Directory.Delete(Environment.SpecialFolder.MyDocuments.ToString(), true); } } } return(strRet); }