private void SaveAndTagFile(string resourceName, Outlook.Attachment att, string entryID) { logger.Debug("resourceName : " + resourceName + "\n"); att.SaveAsFile(resourceName); Backend.AddResource(Utils.RESOURCE_TYPE_FILE, resourceName); Utils.TagResourceForMailItem(entryID, resourceName); }
public System.IO.Stream OpenRead() { if (string.IsNullOrEmpty(tempAttachmentPath)) { tempAttachmentPath = System.IO.Path.GetTempFileName(); _attachment.SaveAsFile(tempAttachmentPath); } return(System.IO.File.Open(tempAttachmentPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite)); }
/// <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 void mySaveAttachAs(Office.IRibbonControl control, bool cancelDefault) { /* * var context = control.Context; * if (isContextInspector(context)) * { * Outlook.Inspector insp = (Outlook.Inspector)context; * //insp.Application. * var currentItem = insp.CurrentItem; * if (currentItem is Outlook.MailItem) * { * Outlook.MailItem mi = (Outlook.MailItem)currentItem; * * } * } */ //string typeName = GetTypeName(control); Outlook.Explorer explorer = Globals.OutlookTagBarAddin.Application.ActiveExplorer(); if (explorer != null && explorer.Selection != null && explorer.Selection.Count > 0) { object item = explorer.Selection[1]; if (item is Outlook.MailItem) { Outlook.MailItem mailItem = item as Outlook.MailItem; Outlook.Attachments attachments = mailItem.Attachments; Outlook.Attachment a = attachments[1]; logger.Debug("a.displayName : " + a.DisplayName + "\n"); logger.Debug("a.pathName : " + a.PathName + "\n"); logger.Debug("a.fileName : " + a.FileName + "\n"); SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "Save Attachment"; sfd.FileName = a.FileName; sfd.Filter = "All files(*.*) | *.*"; sfd.DefaultExt = System.IO.Path.GetExtension(a.FileName); sfd.ShowDialog(); String resourceName = sfd.FileName; logger.Debug("resourceName : " + resourceName + "\n"); a.SaveAsFile(sfd.FileName); Backend.AddResource(Utils.RESOURCE_TYPE_FILE, resourceName); Utils.TagResourceForMailItem(mailItem.EntryID, resourceName); //a.SaveAsFile(@"C:\Users\sudo\Downloads"); cancelDefault = true; } else { cancelDefault = false; } } else { cancelDefault = false; } // nlog }
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); }
private void SavePdfFile(Outlook.Attachment file) { try { file.SaveAsFile(PDF_FILE_PATH + file.FileName); } catch (Exception ex) { LogHelper.Write(ex); } }
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); }
//this function will accept a string path and save the email attachment in that path with a specified format private bool createFoldersAndSave(string path) { if (!System.IO.Directory.Exists(path)) { DialogResult msgResult = MessageBox.Show("Do you want to create the following directory: " + path, "Folder doesn't exist", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); if (msgResult == DialogResult.OK) { System.IO.Directory.CreateDirectory(path); m_Att.SaveAsFile(path + txtUID.Text + " " + cmbDocType.Text + ".pdf"); return(true); } else { return(false); } } else { m_Att.SaveAsFile(path + txtUID.Text + " " + cmbDocType.Text + ".pdf"); return(true); } }
private Signature VerifySignature(Outlook.MailItem mailItem, Outlook.Attachment sigMime, string sigHash, ref CryptoContext context) { var crypto = new PgpCrypto(context); Logger.Trace("Verify detached signature"); var tempfile = Path.GetTempFileName(); sigMime.SaveAsFile(tempfile); var detachedsig = File.ReadAllText(tempfile); File.Delete(tempfile); var clearsig = CreateClearSignatureFromDetachedSignature(mailItem, sigHash, detachedsig); return VerifyClearSignature(ref context, crypto, clearsig); }
private static Attachment CreateTempAttachment(Outlook.Attachment attachment) { var tempAttachment = new Attachment { TempFile = Path.GetTempPath(), FileName = attachment.FileName, DisplayName = attachment.DisplayName, AttachmentType = attachment.Type }; tempAttachment.TempFile = Path.Combine(tempAttachment.TempFile, tempAttachment.FileName); tempAttachment.TempFile = tempAttachment.TempFile + ".pgp"; attachment.SaveAsFile(tempAttachment.TempFile); attachment.Delete(); return tempAttachment; }
// Redemption.Attachment.SaveAsFile() cannot correctly save unicode embedded attachment (Office 2003 + Cache Exchange Mode) // Solution 1: Outlook.Attachment.SaveAsFile() // Solution 2: Redemption.Attachment.EmbeddedMsg.SaveAs( filename, Microsoft.Office.Interop.Outlook.OlSaveAsType.olMSGUnicode) public string GetAttachmentName(OutlookAttachment outlookAttachment) { if (OlAttachmentType.olByReference == outlookAttachment.Type) { return LocalCopyOfFileManager.GetValidFileName(outlookAttachment.PathName, false); } string attachmentName = LocalCopyOfFileManager.GetValidFileName_excl_invalid_chars(outlookAttachment.FileName); string extension = Path.HasExtension(attachmentName) ? Path.GetExtension(attachmentName) : string.Empty; // [7384] If the user created the email using the Word/Excel/Powerpoint File > Save & Send > Send and the // document name contains unicode characters then the resulting attachment will have the unicode characters // replaced by white spaces e.g. "హాయ్ .docx" becomes " .docx" and after the call to remove invalid // chararacters the value is ".docx". If we have display name the try using it before changing the filename // to "Untitled Attachment". In this case the displayname will be "???? .docx" which should be converted to // "____ .docx" since "?" is an invalid filename character. if (string.IsNullOrEmpty(Path.GetFileNameWithoutExtension(attachmentName))) { attachmentName = LocalCopyOfFileManager.GetValidFileName_excl_invalid_chars(outlookAttachment.DisplayName); if (string.IsNullOrEmpty(Path.GetFileNameWithoutExtension(attachmentName))) { attachmentName = UntitledAttachmentTitle; } } if (!attachmentName.EndsWith(extension)) attachmentName += extension; // Bug : Password protected docm files on Outlook 2003 will fail to open as the extension will be incorrect // Bug : when simple mapi is used to create the mail message as the file will be renamed to 8.3 format loosing // Bug : the last character of the file extension. if (OutlookVersion.Convert(outlookAttachment.Application.Version) < OutlookVersion.Version.Outlook2007) { var realExtension = GetExtensionForMasqueradingAttachment(outlookAttachment); if (!string.IsNullOrEmpty(realExtension)) { attachmentName = Path.ChangeExtension(attachmentName, realExtension); } } attachmentName = LocalFileManager.GetLocalCopyOfFileTarget(attachmentName); Logger.LogInfo(string.Format("Save attachment as {0}", attachmentName)); outlookAttachment.SaveAsFile(attachmentName); return attachmentName; }
private bool DecryptMime(Outlook.MailItem mailItem, Outlook.Attachment encryptedMime, ref CryptoContext context, ref string cleartext) { Logger.Trace("Decrypting cypher text."); var tempfile = Path.GetTempFileName(); encryptedMime.SaveAsFile(tempfile); var cyphertext = File.ReadAllBytes(tempfile); File.Delete(tempfile); var clearbytes = DecryptAndVerify(mailItem.To, cyphertext, out context); if (clearbytes == null) { return true; } cleartext = _encoding.GetString(clearbytes); return false; }
private void frmDocControl_VisibleChanged(object sender, EventArgs e) { if (this.Visible == true) { txtUID.Focus(); // below code will preview the attachment in the form if (m_Item.Attachments.Count > 0) { m_Att = m_Item.Attachments[1]; string m_Att_Name = m_Att.FileName; // only pdf files allowed if (m_Att_Name.IndexOf(".pdf") > 0) { // first save onto local system and then pull into browser: easier and no legal consequences of dealing with TP components such as acroPDF string tempAttPath = @"C:\Users\Public\temp.pdf"; acroPDF.ResetText(); //pdfPreviewer.Navigate("about:blank"); if (System.IO.File.Exists(tempAttPath)) { System.IO.File.Delete(tempAttPath); } m_Att.SaveAsFile(tempAttPath); acroPDF.src = tempAttPath; //pdfPreviewer.Navigate(tempAttPath); } else { // if file is not a pdf the form will not be closed but cancelled, hidden MessageBox.Show("Not a PDF"); this.Close(); } } else { // if mail does not have any attachments the form will not be closed but cancelled, hidden MessageBox.Show("No attachments"); this.Close(); } } }
private string SaveAttachment(AppContext ctx, Outlook.Attachment item) { string result = null; if (item.Size != 0) { var fileName = item.GetFileName(); if (string.IsNullOrEmpty(fileName) == false) { fileName = FileHelpers.CleanFileName(fileName, '_'); result = FileHelpers.GenerateUniqueFileName(ctx.Config.TargetFolder, fileName); logger.LogInformation("SaveAttachment\\\"{FileName}\" => \"{OutputFileName}\"", item.FileName, fileName); if (ctx.Config.WhatIf == false) { item.SaveAsFile(result); } } } return(result); }
public void SaveAllAttachmentsMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem senderMenuItem = sender as ToolStripMenuItem; if (senderMenuItem != null) { FolderBrowserDialog fbd = new FolderBrowserDialog(); DialogResult result = fbd.ShowDialog(); string foldername = fbd.SelectedPath; MailItemAttachments mias = (MailItemAttachments)senderMenuItem.Tag; List <MailItemAttachment> miaList = mias.GetMIAs(); foreach (MailItemAttachment mia in miaList) { Outlook.Attachment att = mia.GetAttachment(); Outlook.MailItem mi = mia.GetMailItem(); logger.Debug("would save attachment : " + att.FileName + " for " + mi.EntryID + NL); String path = Path.Combine(foldername, att.FileName); att.SaveAsFile(path); Backend.AddResource(Utils.RESOURCE_TYPE_FILE, path); Utils.TagResourceForMailItem(mi.EntryID, path); } } }
private void Items_ItemAdd(object Item) { try { Outlook.MailItem mailItem = (Outlook.MailItem)Item; if (mailItem.Subject.Contains("NewPOS license file")) { DirectoryInfo storeDir = GetStoreDirectory(mailItem.Body); Outlook.Attachment licenseFile = mailItem.Attachments[0]; string filePath = Path.Combine(storeDir.FullName, licenseFile.FileName); if (File.Exists(filePath)) { File.Delete(filePath); } licenseFile.SaveAsFile(filePath); } } catch { MessageBox.Show($"Не удалось сохранить файл лицензии из письма {((Outlook.MailItem)Item).Subject}"); return; } }
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); }
protected string GetExtensionForMasqueradingAttachment(OutlookAttachment attachment) { if (attachment.FileName.Contains('~')) // only interested in 8.3 formated file names. { var extension = Path.GetExtension(attachment.FileName); if (!string.IsNullOrEmpty(extension)) { using (var tfc = new TempFileController()) { var tempfile = tfc.GetTempFilename(extension.TrimStart('.'), true); attachment.SaveAsFile(tempfile); using (IFile file = new Workshare.FCS.Lite.Interface.File(tempfile, attachment.DisplayName)) { switch (file.FileType) { case FileType.WordDocumentX: return "docx"; case FileType.ExcelSheetX: return "xlsx"; case FileType.PowerPointX: return "pptx"; } } } } } return string.Empty; }
// This method is called every time an email is sent. private void Application_ItemSend(object Item, ref bool Cancel) { if (EnableAsposeWordsMetadata) { try { Outlook.MailItem thisEmail = Item as Outlook.MailItem; bool flgPassword = false; for (int i = thisEmail.Attachments.Count; i > 0; i--) { Outlook.Attachment attachment = thisEmail.Attachments[i]; // Save the attachment in the temp location. int attachmentIndex = attachment.Index; string tempPath = Path.GetTempPath(); string tempFileName = tempPath + attachment.FileName; attachment.SaveAsFile(tempFileName); // Check the file format for Microsoft Word documents. FileFormatInfo info = FileFormatUtil.DetectFileFormat(tempFileName); bool wordAttachment = false; switch (info.LoadFormat) { case LoadFormat.Doc: case LoadFormat.Dot: case LoadFormat.Docx: case LoadFormat.Docm: case LoadFormat.Dotx: case LoadFormat.Dotm: case LoadFormat.FlatOpc: case LoadFormat.Rtf: case LoadFormat.WordML: case LoadFormat.Html: case LoadFormat.Mhtml: case LoadFormat.Odt: case LoadFormat.Ott: case LoadFormat.DocPreWord60: wordAttachment = true; break; } // If a Word Attachment is found: if (wordAttachment) { try { Aspose.Words.Document doc = new Words.Document(tempFileName); // Remove if there is any protection on the document. ProtectionType protection = doc.ProtectionType; if (protection != ProtectionType.NoProtection) { doc.Unprotect(); } // Remove all built-in and Custom Properties. doc.CustomDocumentProperties.Clear(); doc.BuiltInDocumentProperties.Clear(); // Password will be removed if the document is password protected. if (protection != ProtectionType.NoProtection) { doc.Protect(protection); } // Save the file back to temp location. doc.Save(tempFileName); // Replace the original attachment. thisEmail.Attachments.Remove(attachmentIndex); thisEmail.Attachments.Add(tempFileName, missing, attachmentIndex, missing); } catch (Words.IncorrectPasswordException ex) { flgPassword = true; } catch (Exception ex) { throw ex; } } if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } if (flgPassword) { MessageBox.Show("Password protected documents cannot be processed for Metadata cleaning"); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message, "Error"); Cancel = true; } } }
public ContactCollectionType GetItems() { ContactCollectionType result = new ContactCollectionType(); foreach (OutlookInterop.ContactItem item in mAPI.Items.OfType <OutlookInterop.ContactItem>()) { ContactType tmpItem = new ContactType(); tmpItem.OriginId = item.EntryID; tmpItem.OriginSystem = OriginSystemEnum.Outlook; tmpItem.LastModTime = item.LastModificationTime; tmpItem.DisplayName = item.FullName; tmpItem.Title = item.Title; tmpItem.Surname = item.LastName; tmpItem.MiddleName = item.MiddleName; tmpItem.GivenName = item.FirstName; tmpItem.AddName = item.Suffix; tmpItem.Company = item.CompanyName; tmpItem.VIP = (item.Importance == OutlookInterop.OlImportance.olImportanceHigh); tmpItem.SaveAs = item.FileAs; if (item.Birthday.Year < 4000) { tmpItem.Birthday = item.Birthday; } if (item.Anniversary.Year < 4000) { tmpItem.AnniversaryDay = item.Anniversary; } tmpItem.Notes = item.Body; tmpItem.IMAddress = item.IMAddress; //========================== //private data tmpItem.PrivateMailAddress = GetMailStruct(item.Email1DisplayName, item.Email1Address, item.Email1AddressType); //if no valid mail address could be delivered if ((tmpItem.PrivateMailAddress.Address ?? "") == "") { tmpItem.PrivateMailAddress.Address = (tmpItem.IMAddress ?? "").Contains('@') ? tmpItem.IMAddress : null; } tmpItem.PrivateMobileNumber = item.MobileTelephoneNumber; tmpItem.PrivatePhoneNumber = item.HomeTelephoneNumber; tmpItem.PrivateFaxNumber = item.HomeFaxNumber; if ((item.HomeAddressStreet != null) || (item.HomeAddressPostalCode != null) || (item.HomeAddressCity != null) || (item.HomeAddressCountry != null)) { //tmpItem.PrivateLocation = new Address(); tmpItem.PrivateLocation.Street = item.HomeAddressStreet?.Split(' ').First(); tmpItem.PrivateLocation.Number = tmpItem.PrivateLocation.Street?.Substring(tmpItem.PrivateLocation.Street.Length - 1); tmpItem.PrivateLocation.Zip = item.HomeAddressPostalCode; tmpItem.PrivateLocation.City = item.HomeAddressCity; tmpItem.PrivateLocation.Country = item.HomeAddressCountry; } //========================== //business data tmpItem.BusinessMailAddress = GetMailStruct(item.Email2DisplayName, item.Email2Address, item.Email2AddressType); //if no valid mail address could be delivered if ((tmpItem.BusinessMailAddress.Address ?? "") == "") { tmpItem.BusinessMailAddress.Address = (tmpItem.IMAddress ?? "").Contains('@') ? tmpItem.IMAddress : null; } tmpItem.BusinessMobileNumber = item.Business2TelephoneNumber; tmpItem.BusinessPhoneNumber = item.BusinessTelephoneNumber; tmpItem.BusinessFaxNumber = item.BusinessFaxNumber; if ((item.BusinessAddressStreet != null) || (item.BusinessAddressPostalCode != null) || (item.BusinessAddressCity != null) || (item.BusinessAddressCountry != null)) { //tmpItem.BusinessLocation = new Address(); tmpItem.BusinessLocation.Street = item.BusinessAddressStreet?.Split(' ').First(); tmpItem.BusinessLocation.Number = tmpItem.BusinessLocation.Street?.Substring(tmpItem.BusinessLocation.Street.Length - 1); tmpItem.BusinessLocation.Zip = item.BusinessAddressPostalCode; tmpItem.BusinessLocation.City = item.BusinessAddressCity; tmpItem.BusinessLocation.Country = item.BusinessAddressCountry; } //========================== //handle photo if (item.HasPicture) { OutlookInterop.Attachment tmpPhotofile = item.Attachments["ContactPicture.jpg"]; //if a photo is attached if (tmpPhotofile != null) { string tmpFilename = Environment.GetEnvironmentVariable("TEMP").TrimEnd('\\') + '\\' + item.EntryID + ".jpg"; tmpPhotofile.SaveAsFile(tmpFilename); tmpItem.PictureTmpFilename = tmpFilename; } Marshal.ReleaseComObject(tmpPhotofile); } result.Add(tmpItem); } return(result); }
public override bool?process(Outlook.MailItem subject, IControl <FileInfo, IValidationConfigCol <IValidator <string, string>, EmailValidatorConfig>, Dictionary <ValidResultConfig, Dictionary <String, ValidResults> > > controller, IDictionary <string, string> configs = null) { String moveto = null, rhtml = null; bool clearCat = false, movetoinbox = false; if (subject.Attachments?.Count > 0) { Outlook.Attachment attachment = null; var attachments = subject.Attachments; Dictionary <EmailValidatorConfig, IEnumerable <Tuple <String, String, Boolean?> > > avalCols = new Dictionary <EmailValidatorConfig, IEnumerable <Tuple <String, String, Boolean?> > >(); Dictionary <ValidResultConfig, Dictionary <String, ValidResults> > resultsCol = new Dictionary <ValidResultConfig, Dictionary <String, ValidResults> >(); try { for (int i = 1; i <= attachments.Count; i++) { if (stopOnReject || error) { break; } attachment = attachments[i]; if (attachment.FileName.Split(".").Last().ToLower().Equals("xlsm")) { var d = Directory.CreateDirectory($@"temp\{Guid.NewGuid()}"); var path = Tools.GetUniqueFileName(Path.Combine(d.FullName, attachment.FileName.Replace("~", "").Trim())); attachment.SaveAsFile(path); Logger.Log($"{attachment.FileName} saved to {path} ..."); if (controller == null) { ExecuteValidationConfig(vconfigCol, avalCols, path, resultsCol); } else { resultsCol.Concat(controller.execute(new FileInfo(path), null, configs)); } } Logger.WriteToConsole($"Successfully validated {attachment.FileName}"); // Logger.WriteToConsole($"Logged to DB for [{path}], result:{DBHelper.InsertOptAttachmentReceived(new OptAttachmentReceived() { AttachmentFileName = attachment.FileName, ExecutionTime = DateTime.Now, ImportErrorMessage = String.Join(",", results.Select(r => $"[{r.Key}][{r.Value}]")), Subject = mail.Subject, SenderEmailAddress = evals[ConfigHelper.Sender_Email_Address.name], RecievedTime = mail.ReceivedTime, _ImportResult = success })}"); } var guid = Guid.NewGuid().ToString(); var evals = new Dictionary <String, String>() { { ConfigHelper.Email_Date, subject.ReceivedTime.ToString("MM/dd/yyyy HH:mm:ss") }, { ConfigHelper.Email_Subject, Tools.SafeSubstring(subject.Subject, 0, 199) }, { ConfigHelper.Sender_Email_Address, OutlookHelper.GetSenderEmailAddr(subject) }, { ConfigHelper.SN, ConsolidateHelper.TimeLapsedID } }; var pstpath = configs.ContainsKey(PSTconfigsEnum.pstPath.ToString()) ? Directory.CreateDirectory(pnc?.execute(configs[PSTconfigsEnum.pstPath.ToString()], null, null) ?? configs[PSTconfigsEnum.pstPath.ToString()]).FullName : ""; if (success && resultsCol.Any()) { foreach (var aresultsCol in resultsCol) { var tdpath = $@"temp\${Guid.NewGuid()}"; var dpath = pnc?.execute(aresultsCol.Key.targetPath, null, null) ?? aresultsCol.Key.targetPath; if (File.Exists(dpath)) { if (!Tools.FileOverWriteCopy(dpath, tdpath)) { throw new Exception($"Unable to create temp data result [{dpath}] to [{tdpath}]"); } } else if (File.Exists(aresultsCol.Key.tempatePath) && !Tools.FileOverWriteCopy(aresultsCol.Key.tempatePath, tdpath)) { throw new Exception($"Unable to create temp data result [{aresultsCol.Key.tempatePath}] to [{tdpath}] with template [{aresultsCol.Key.tempatePath}]"); } var bindmaps = getBindMaps(aresultsCol.Key); configs[XCDconfigsEnum.cwwsn.ToString()] = aresultsCol.Key.targetSheet ?? Path.GetFileNameWithoutExtension(dpath); var headersID = aresultsCol.Key.headersPath; if (!String.IsNullOrWhiteSpace(headersID) && !DATARSTHeader.headers.ContainsKey(headersID)) { YamlStream yaml = new YamlStream(); using (var sr = new FileInfo(headersID).OpenText()) yaml.Load(sr); (yaml.Documents[0].RootNode as YamlMappingNode).Children.Where(e => !ConsolidateHelper.isIgnoredHeader(e.Value?.ToString())).Select(e => new DATARSTHeader(e.Value.ToString(), headersID, DATARSTHeader.headers.GetValueOrDefault(headersID)?.FirstOrDefault(h => h.name == e.Value.ToString())?.value ?? 0)).ToArray(); } var headers = DATARSTHeader.headers?.GetValueOrDefault(headersID); var sqlPFile = String.IsNullOrWhiteSpace(aresultsCol.Key.sqlPath) ? "" : (pnc?.execute(aresultsCol.Key.sqlPath, null, null) ?? aresultsCol.Key.sqlPath); if (File.Exists(aresultsCol.Key.sqlTemplatePath)) { if (!Tools.FileOverWriteCopy(aresultsCol.Key.sqlTemplatePath, sqlPFile)) { throw new Exception("Unable to create temp data result @:" + tdpath); } } configs[PSTconfigsEnum.template.ToString()] = aresultsCol.Key.sqlQueryTemplate; Directory.CreateDirectory(Path.GetDirectoryName(sqlPFile)); Directory.CreateDirectory(Path.GetDirectoryName(dpath)); using (PersistenceSQLProcessor pp = String.IsNullOrWhiteSpace(sqlPFile) ? null : new PersistenceSQLProcessor(sqlPFile, configs.ContainsKey(PSTconfigsEnum.pstConnString.ToString()) && !String.IsNullOrWhiteSpace(configs[PSTconfigsEnum.pstConnString.ToString()]) ? configs[PSTconfigsEnum.pstConnString.ToString()] : "", bindmaps)) using (XlsxResultProcessor p = String.IsNullOrWhiteSpace(dpath) ? null : new XlsxResultProcessor(tdpath, configs[XCDconfigsEnum.cwwsn.ToString()], bindmaps, headers)) success = new XlsxConsolidator() { headers = headers, evals = evals, bindmaps = bindmaps }.consolidate(new List <IProcessor <IDictionary <String, String>, Object> >() { pp, p }, aresultsCol.Value, configs); //Transfering consolation results to designated paths if (!mergeTempResults(tdpath, dpath)) { throw new Exception($"[{dpath}] transfer filed..."); } if (!String.IsNullOrWhiteSpace(sqlPFile) && !Tools.FileOverWriteMove(sqlPFile, sqlPFile + ".sql")) { throw new Exception($"[{sqlPFile}] transfer filed..."); } } if (success) { moveto = configs[EPconfigsEnum.sucFolder.ToString()]; try { if (configs.ContainsKey(EPconfigsEnum.saveMailPath.ToString())) { saveMailtoLocal(subject, configs[EPconfigsEnum.saveMailPath.ToString()]); } } catch (Exception ex) { Logger.Log(ex); } } else { throw new Exception($"Attachment [{attachment.FileName}] consolidation filed..."); } } try { if (configs.ContainsKey(EPconfigsEnum.emailLogConnString.ToString())) { foreach (var fname in resultsCol.SelectMany(r => r.Value)) { using (PersistenceSQLProcessor pp = new PersistenceSQLProcessor(Path.Combine(pstpath, guid + ".log"), configs[EPconfigsEnum.emailLogConnString.ToString()], null)) Logger.WriteToConsole($"Logged to DB for [{fname.Key}], result:{pp.process(evals.Append(new KeyValuePair<string, string>("ImportResult", fname.Value.Any(v => v.Value == false) ? "FAIL" : "SUCCESS")).Append(new KeyValuePair<string, string>("ImportErrorMessage", Tools.SafeSubstring($"[{String.Join(",", fname.Value?.Select(v => $"{{\"{v.Key}\":\"{v.Value?.ToString() ?? "null"}\"}}"))}]", 0, 499))).Append(new KeyValuePair<string, string>("AttachmentFileName", Tools.SafeSubstring(Path.GetFileName(fname.Key), 0, 99))).Append(new KeyValuePair<string, string>("Filename", Tools.SafeSubstring(Path.GetFileName(currentEmailFilePath ?? ""), 0, 99))).Append(new KeyValuePair<string, string>("guid", guid)).ToDictionary(prop => prop.Key, prop => prop.Value), null, new Dictionary<String, String>() { { PSTconfigsEnum.template.ToString(), configs[EPconfigsEnum.emailLogTemplate.ToString()] } })}"); } } } catch (Exception ex) { Logger.Log(ex); } } catch (Exception ex) { error = true; Logger.Log(ex); rhtml = ex.StackTrace.ToString(); success = false; } finally { Marshal.ReleaseComObject(attachment); attachment = null; } if (error) { new EmailResponseController().execute(subject, new EmailResponseConfig() { oApp = oApp, defaultMessage = rhtml ?? "Error occurred!", replyRecipients = configs[EPconfigsEnum.AdminEmail.ToString()]?.Split(";") }); moveto = configs[EPconfigsEnum.rdestFolder.ToString()]; if (String.IsNullOrEmpty(moveto) || moveto == configs[EPconfigsEnum.destFolder.ToString()]) { clearCat = true; } Logger.WriteToConsole($"Prepared internal error response for [{subject.Subject}]"); } else { if (success) { clearCat = true; Logger.WriteToConsole($"Cleared mark for [{subject.Subject}]"); } if (avalCols.Any()) { foreach (var avalcol in avalCols) { var t = validColsCols.First(vc => vc == avalcol.Key); new EmailResponseController().execute(subject, new EmailResponseConfig() { oApp = oApp, replyRecipients = avalcol.Value == null ? t.sucEmails : t.rejEmails, template = avalcol.Value == null ? t.sucTemplate : t.rejTemplate, rows = avalcol.Value, sentonbehalf = configs.ContainsKey(EPconfigsEnum.sentonbehalf.ToString()) ? configs[EPconfigsEnum.sentonbehalf.ToString()] : null, ResultMap = t.ResultMap }); if (!success) { moveto = t.rejFolder; if (moveto == null) { clearCat = true; } } Logger.WriteToConsole($"Sending response template [{(success ? t.sucTemplate : t.rejTemplate)}] for [{subject.Subject}]"); } } else if (resultsCol?.Any() == true) { new EmailResponseController().execute(subject, new EmailResponseConfig() { oApp = oApp, template = configs.ContainsKey(EPconfigsEnum.sucTemplate.ToString()) ? new FileInfo(configs[EPconfigsEnum.sucTemplate.ToString()]) : null, sentonbehalf = configs.ContainsKey(EPconfigsEnum.sentonbehalf.ToString()) ? configs[EPconfigsEnum.sentonbehalf.ToString()] : null, savesentfolder = configs.ContainsKey(EPconfigsEnum.saveSentFolder.ToString()) ? configs[EPconfigsEnum.saveSentFolder.ToString()] : null }); Logger.WriteToConsole($"Sending response success template for [{subject.Subject}]"); } else if (success) { movetoinbox = true; Logger.WriteToConsole($"Moving to [{configs[EPconfigsEnum.retfolder.ToString()]}] due to having nothing to load..."); } else { Logger.WriteToConsole($"Unknown error occurred for [{subject.Subject}] ..."); } } } else { movetoinbox = true; } if (saveChanges) { if (movetoinbox) { clearCat = true; moveto = configs[EPconfigsEnum.retfolder.ToString()]; } if (clearCat) { subject.Categories = null; subject.Save(); } if (moveto != null && moveto != configs[EPconfigsEnum.destFolder.ToString()]) { var movetohandle = oApp.Session.Stores[configs[EPconfigsEnum.storename.ToString()]].GetRootFolder().Folders[moveto]; subject.Move(movetohandle); Marshal.ReleaseComObject(movetohandle); movetohandle = null; Logger.WriteToConsole($"Moved [{subject.Subject}] to [{moveto}]"); } } return(success); }
/// <summary> /// Get the package file from outlook attachments (the attachment file is copied to the file system) /// </summary> /// <param name="messageItem">the message item containing the attachments</param> /// <returns>a file system path to a file containing a package</returns> public static string GetPackageFileFromAttachments(MessageItem messageItem) { if (messageItem == null) { throw new ArgumentNullException("messageItem"); } string sTempDirectory = messageItem.TempDirectory; System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(sTempDirectory)); if (!Directory.Exists(sTempDirectory)) { string sParentDirectory = Path.GetDirectoryName(sTempDirectory); if (!Directory.Exists(sParentDirectory)) //We could have received the mail item { string sTempFolder = Path.GetFileName(sTempDirectory); System.Diagnostics.Debug.Assert(sTempFolder.EndsWith(Constants.TempDirExt)); sTempDirectory = System.IO.Path.Combine(System.IO.Path.GetTempPath(), sTempFolder); } Directory.CreateDirectory(sTempDirectory); } //Find the package and also check for the presence of several .velodoc attachments int iPackageCount = 0; Outlook.Attachment objPackageAttachment = null; foreach (Outlook.Attachment objAttachment in messageItem.Attachments) { if ((objAttachment.Type != Outlook.OlAttachmentType.olByReference) && (objAttachment.Type != Outlook.OlAttachmentType.olByValue)) { continue; } if (Path.GetExtension(objAttachment.FileName).Equals(Constants.VelodocExt)) { iPackageCount++; if (objPackageAttachment == null) { objPackageAttachment = objAttachment; } } } //If no package can be found among the file attachments, return null if (objPackageAttachment == null) { System.Diagnostics.Debug.Assert(iPackageCount == 0); return(null); } //Raise an exception if there is more than one package in the attachments if (iPackageCount > 1) { throw new NotSupportedException(Properties.Resources.ExceptionNoMoreThanOnePackageAsAttachment); } //if we have reached here, we have one single package as file attachment System.Diagnostics.Debug.Assert(iPackageCount == 1); //Build a full file path where to copy the attachment string sPackageFileRet = Path.Combine(sTempDirectory, objPackageAttachment.FileName); //TODO: Can we assume we get a valid file name? //If the file already exists on disk, remove it FileInfo objFileInfo = new FileInfo(sPackageFileRet); if (objFileInfo.Exists) { objFileInfo.Attributes &= ~FileAttributes.ReadOnly; objFileInfo.Delete(); } //Copy the file attachement to the temp directory objPackageAttachment.SaveAsFile(sPackageFileRet); return(sPackageFileRet); }