void OutlookMail() { try { DateTime DTime = DateTime.Now; gvwEODProcess.ExportToExcelOld(_core.ReportPathOut + "\\EODMail" + DTime.Hour + DTime.Minute + DTime.Second + ".xls"); Outlook.Application oApp = new Outlook.Application(); Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); oMsg.Subject = "Өдөр өндөрлөлтийн процесс"; oMsg.Body = _core.TxnDate.ToShortDateString() + "-н өдөр өндөрлөлтийн процессийн тайлан ."; String sSource = _core.ReportPathOut + "\\EODMail" + DTime.Hour + DTime.Minute + DTime.Second + ".xls"; String sDisplayName = "Хавсралт файл"; int iPosition = 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; Outlook.Attachment oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName); oMsg.Display(true); oAttach = null; oMsg = null; oApp = null; } catch { MessageBox.Show("Алдаа гарлаа ."); } }
/// <summary> /// Code to send a mail by attaching log file using log4net /// </summary> public void sendEMailThroughOUTLOOK() { try { SplashScreenManager.ShowForm(this, typeof(WaitForm1), true, true, false); SplashScreenManager.Default.SetWaitFormDescription("Sending aail to administrator..."); Outlook.Application oApp = new Outlook.Application(); Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); oMsg.HTMLBody = "Hello, Here is the log file!!"; String sDisplayName = "OTTOPro Log File"; int iPosition = (int)oMsg.Body.Length + 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; string st = Environment.ExpandEnvironmentVariables(@"%AppData%"); Outlook.Attachment oAttach = oMsg.Attachments.Add(st + "\\OTTOPro.log", iAttachType, iPosition, sDisplayName); oMsg.Subject = "OTTOPro Log File"; Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("*****@*****.**"); oRecip.Resolve(); oMsg.Send(); oRecip = null; oRecips = null; oMsg = null; oApp = null; SplashScreenManager.CloseForm(false); XtraMessageBox.Show("Log file mail sent to administrator.!"); } catch (Exception ex) {} }
public static int sendEmail(String fileName) { try { Outlook.Application oApp = new Outlook.Application(); Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); string toEmail = ConfigurationManager.AppSettings["to"].ToString(); oMsg.HTMLBody = String.Format("Dear Eng. {0}, please find the attachements below.", toEmail); Outlook.Attachment oAttach = oMsg.Attachments.Add(fileName); oMsg.Subject = String.Format("XXXX & YYYYY for {0}", getTime()); Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("XXXXYYYY"); oRecip.Resolve(); ((Outlook._MailItem)oMsg).Send(); writeLog(String.Format("Email sent is successfully sent for {0}.", getTime())); System.Threading.Thread.Sleep(1000); // Clean up. oRecip = null; oRecips = null; oMsg = null; oApp = null; return(1); } catch (Exception exc) { writeLog(exc.Message); return(0); } }
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 static void Method2() { // Create the Outlook application. Outlook.Application outlookApp = new Outlook.Application(); Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem); //Add an attachment. String attachmentDisplayName = "MyAttachment"; // Attach the file to be embedded string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed Outlook.Attachment oAttach = mailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName); mailItem.Subject = "Sending an embedded image"; string imageContentid = "someimage.jpg"; // Content ID can be anything. It is referenced in the HTML body oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid); mailItem.HTMLBody = String.Format( "<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>", imageContentid); // Add recipient Outlook.Recipient recipient = mailItem.Recipients.Add("*****@*****.**"); recipient.Resolve(); // Send. mailItem.Send(); }
public void init(Outlook.Attachment attach) { attachment = attach; System.IO.FileInfo fi = new System.IO.FileInfo(attachment.FileName); lNom.Text = "Nom : " + fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length); lType.Text = "Type : " + fi.Extension.ToString(); lTaille.Text = "Taille : " + attachment.Size + " o"; IDictionary<string, string> parameters = new Dictionary<string, string>(); parameters[SessionParameter.BindingType] = BindingType.AtomPub; XmlNode rootNode = Config1.xmlRootNode(); parameters[SessionParameter.AtomPubUrl] = rootNode.ChildNodes.Item(0).InnerText + "atom/cmis"; parameters[SessionParameter.User] = rootNode.ChildNodes.Item(1).InnerText; parameters[SessionParameter.Password] = rootNode.ChildNodes.Item(2).InnerText; SessionFactory factory = SessionFactory.NewInstance(); ISession session = factory.GetRepositories(parameters)[0].CreateSession(); // construction de l'arborescence string id = null; IItemEnumerable<IQueryResult> qr = session.Query("SELECT * from cmis:folder where cmis:name = 'Default domain'", false); foreach (IQueryResult hit in qr) { id = hit["cmis:objectId"].FirstValue.ToString(); } IFolder doc = session.GetObject(id) as IFolder; TreeNode root = treeView.Nodes.Add(doc.Id, doc.Name); AddVirtualNode(root); }
/// <summary> /// Gets the approximate size of an Outlook Attachment (includes not only file size but also Outlook attachment properties) /// </summary> /// <param name="attachment"></param> /// <returns></returns> public static long GetAttachmentSize(Outlook.Attachment attachment) { long lSizeRet = attachment.Size; System.Diagnostics.Trace.WriteLine("MAPIHelper: Attachment size is " + lSizeRet.ToString()); return(lSizeRet); }
private bool checkIfInline(Outlook.Attachment att) { switch (att.Type) { case Outlook.OlAttachmentType.olEmbeddeditem: case Outlook.OlAttachmentType.olByReference: case Outlook.OlAttachmentType.olOLE: return(true); } Outlook.PropertyAccessor prop = att.PropertyAccessor; object emCID = prop.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E"); string emMime = (prop.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001E") != null ? att.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001E").ToString() : ""); if (!att.Type.Equals(Microsoft.Office.Interop.Outlook.OlAttachmentType.olOLE) && (!emMime.ToLower().Contains("image") || (emCID == null || (emCID.Equals(""))))) { return(true); } if (prop.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3713001E") is null || prop.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003") == 4) { return(true); } return(false); }
private static Outlook.Attachment FindPgpMime(Outlook.MailItem mailItem, out Outlook.Attachment sigMime) { var foundPgpMime = false; Outlook.Attachment encryptedMime = null; sigMime = null; foreach (Outlook.Attachment attachment in mailItem.Attachments) { var mimeEncoding = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F"); Logger.Trace("MIME: Attachment type: " + mimeEncoding); if (mimeEncoding == PgpEncryptedMime) { Logger.Trace("MIME: Found" + PgpEncryptedMime); foundPgpMime = true; } else if (mimeEncoding == PgpSignatureMime) { Logger.Trace("MIME: Found" + PgpSignatureMime); sigMime = attachment; } else if (foundPgpMime && encryptedMime == null && mimeEncoding == "application/octet-stream") { // Should be first attachment *after* PGP_MIME version identification Logger.Trace("MIME: Found octet-stream following pgp-encrypted."); encryptedMime = attachment; } } return encryptedMime; }
private static bool AttachmentIsInlineImage(Outlook.MailItem mailItem, Outlook.Attachment attachment) { Debug.Assert(attachment != null); const string PR_ATTACH_METHOD = "http://schemas.microsoft.com/mapi/proptag/0x37050003"; const string PR_ATTACH_FLAGS = "http://schemas.microsoft.com/mapi/proptag/0x37140003"; if (mailItem.BodyFormat == Outlook.OlBodyFormat.olFormatPlain) { // if this is a plain text email, every attachment is a non-inline attachment return(false); } else if (mailItem.BodyFormat == Outlook.OlBodyFormat.olFormatRichText) { // if the body format is RTF, the non-embedded attachment would be of the PR_ATTACH_METHOD property is not 6 (ATTACH_OLD) return((int)attachment.PropertyAccessor.GetProperty(PR_ATTACH_METHOD) == 6); } else if (mailItem.BodyFormat == Outlook.OlBodyFormat.olFormatHTML) { // if the body format is HTML, the non-embedded attachment would be of the PR_ATTACH_FLAGS property is not 4 (ATT_MHTML_REF) return((int)attachment.PropertyAccessor.GetProperty(PR_ATTACH_FLAGS) == 4); } else { Debug.Assert(false); return(false); } }
private void MailButton_Click(object sender, RoutedEventArgs e) { try { Outlook.Application _app = new Outlook.Application(); Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem); string filepath = @"D:\Documents\EMPLOYEE PERFORMANCE REVIEW.docx"; mail.To = "*****@*****.**"; mail.Subject = "Performance Reviews"; mail.Body = "benefit enrollments test"; mail.Importance = Outlook.OlImportance.olImportanceNormal; Outlook.Attachment file = mail.Attachments.Add(filepath, Outlook.OlAttachmentType.olByValue, 1, filepath); mail.Send(); MessageBox.Show("message sent"); _app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(_app); } catch { MessageBox.Show("failed to send email"); } }
/// <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 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 }
private void SavePdfFile(Outlook.Attachment file) { try { file.SaveAsFile(PDF_FILE_PATH + file.FileName); } catch (Exception ex) { LogHelper.Write(ex); } }
public void CreateMailItem(String email, String path) { mail = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as Outlook.MailItem; mail.Subject = Subject; mail.Body = EmailBody; Outlook.Attachment attach = mail.Attachments.Add(path); mailrecipents = mail.Recipients; rec = mailrecipents.Add(email); rec.Resolve(); mail.Send(); }
public static string GetFileName(this Outlook.Attachment item) { try { return(item.FileName); } catch (COMException) { } return(default);
private void ProcessEmbeddedItemAttachment(AppContext ctx, Outlook.Attachment item) { var path = SaveAttachment(ctx, item); if (string.IsNullOrEmpty(path) == false && ctx.Config.WhatIf == false) { var embeddedMessage = outlook.OpenSharedItem(path); ProcessItem(ctx, embeddedMessage); } }
public Boolean SendEmailLeyendaRPA(string mailDirection, string mailSubject, string mailContent, string mailGreeting, string mailFarewell) { try { var oApp = new Application(); NameSpace ns = oApp.GetNamespace("MAPI"); var f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); System.Threading.Thread.Sleep(1000); var mailItem = (MailItem)oApp.CreateItem(OlItemType.olMailItem); Microsoft.Office.Interop.Outlook.Attachment attachment = mailItem.Attachments.Add( @"C:\RPA\RPA.png" , OlAttachmentType.olEmbeddeditem , null , "Some image display name" ); string imageCid = "RPA.png@123"; attachment.PropertyAccessor.SetProperty( "http://schemas.microsoft.com/mapi/proptag/0x3712001E" , imageCid ); mailGreeting = String.Format("<p style=\"font-family:Arial;\">{0}</p>", mailGreeting); mailContent = String.Format("<p align=\"justify\" style=\"font-family:Arial; \">{0}</p>", mailContent); mailFarewell = String.Format("<p style=\"font-family:Arial; \">{0}</p><p><img src=\"cid:{1}\"><h6 style=\"margin:0; font-family:Arial; font-weight:normal;\">Por favor no responda este correo</h6><br></p>" , mailFarewell, imageCid); mailContent = String.Format("<body>{0}{1}{2}<\body>", mailGreeting, mailContent, mailFarewell); mailItem.Subject = mailSubject; mailItem.HTMLBody = mailContent; mailItem.To = mailDirection; mailItem.Send(); } catch (System.Exception ex) { return(false); } finally { } return(true); }
public override void SendMessage() { Outlook.MailItem mail = oApp.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; try { mail.Subject = this.Subject; //mail.Body = this.MessageBody; // Add recipient using display name, alias, or smtp address AddRecipients(mail); //Add All Attachments to the Message foreach (IAttachment attachment in this.Attachments) { Outlook.Attachment oAttach = mail.Attachments.Add(attachment.AttachemntPath, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); oAttach = null; } //If There Are Recipient to send the message to then send the message. if (mail.Recipients.Count > 0) { Outlook.Inspector myInspector = mail.GetInspector; String text; text = this.MessageBody + mail.HTMLBody; mail.HTMLBody = text; if (this.MessagePriority == enumMessagePriority.Low) { mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceLow; } if (this.MessagePriority == enumMessagePriority.Medium) { mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal; } if (this.MessagePriority == enumMessagePriority.High) { mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh; } mail.Save(); mail.Send(); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("Error Send email Via Oultook - Error : " + ex.Message); } finally { //Explicitly release objects. mail = null; } }
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 void sendEMailThroughOUTLOOK() { try { // Create the Outlook application. Outlook.Application oApp = new Outlook.Application(); // Create a new mail item. Outlook._MailItem oMsg = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); // Set HTMLBody. //add the body of the email // "Dear Admin, You have recieved an enquiry onyour Website. Following are the details of enquiry:<br/><br/>Name: " + TextBox2.Text + "<br/>Address: " + TextBox3.Text + ", " + TextBox4.Text + "<br/>Phone: " + TextBox5.Text + "<br/>Email: " + TextBox2.Text + "<br/>Query: " + TextBox6.Text+"<br/> Regards, <br/> Veritas Team" oMsg.HTMLBody = "Hi,\n \n <br/> <br/>Automation Execution has been started \n<br/><br/> Thanks & Regards \n<br/> Raghu Ram Reddy<br/><br/><br/>***This is an Auto generated mail***"; // oMsg.HTMLBody = "Automation Execution has been started!!"; //Add an attachment. String sDisplayName = "MyAttachment"; int iPosition = (int)oMsg.Body.Length + 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; // now attached the file Outlook.Attachment oAttach = oMsg.Attachments.Add(@"D:\\Suite_Driver.xlsx", iAttachType, iPosition, sDisplayName); //Subject line oMsg.Subject = "Automation Execution has been started!!"; // Outlook.MailItem mail; // Add a recipient. Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; // Change the recipient in the next line if necessary. // Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("*****@*****.**"); // oRecip.Resolve(); Outlook.Recipient oRecip2 = (Outlook.Recipient)oRecips.Add("*****@*****.**"); oRecip2.Resolve(); //Outlook.Recipient oRecip3 = (Outlook.Recipient)oRecips.Add("*****@*****.**"); //oRecip3.Resolve(); // Send. oMsg.Send(); // Clean up. oRecip2 = null; oRecips = null; oMsg = null; oApp = null; }//end of try block catch (Exception ex) { Console.WriteLine(ex); } //end of catch } //end of Email Method
private bool isImageAttachment(Outlook.Attachment attachment) { foreach (string extension in Constants.IgnoredMatchRecipientsExtentions) { // Confirm that the attachment is a text file. if (System.IO.Path.GetExtension(attachment.FileName) == extension) { return(true); } } return(false); }
private void SaveAttachmentMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem senderMenuItem = sender as ToolStripMenuItem; if (senderMenuItem != null) { MailItemAttachment mia = (MailItemAttachment)senderMenuItem.Tag; Outlook.MailItem mailItem = mia.GetMailItem(); Outlook.Attachment att = mia.GetAttachment(); string resourceName = ShowDialogAndGetPath(senderMenuItem, att); SaveAndTagFile(resourceName, att, mailItem.EntryID); } }
public static void SendEmailUsingOUTLOOK(string attachmentName) { string sonarUrl = ConfigurationManager.AppSettings["sonarUrl"]; string mailFrom = ConfigurationManager.AppSettings["mailFrom"]; string mailTo = ConfigurationManager.AppSettings["mailTo"]; try { Log("Preparing mail..\n"); // Create the Outlook application. Outlook.Application oApp = new Outlook.Application(); // Create a new mail item. Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); // Set HTMLBody. //add the body of the email var dateFormat = ConfigurationManager.AppSettings["DateFormat"].ToString(); oMsg.HTMLBody = ConfigurationManager.AppSettings["mailBody"].ToString().Replace("REPORTDATE", DateTime.Now.ToString(dateFormat)).Replace("SONARURL", sonarUrl); //"Hi Team,<br>" + ConfigurationManager.AppSettings["mailSubject"] + DateTime.Now.ToString("MMM yyyy"); //Add an attachment. // String sDisplayName = string.Format("{0}", attachmentName); int iPosition = (int)oMsg.Body.Length + 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; //now attached the file Outlook.Attachment oAttach = oMsg.Attachments.Add (attachmentName, iAttachType, iPosition); //Subject line oMsg.Subject = ConfigurationManager.AppSettings["mailSubject"].Replace("REPORTDATE", DateTime.Now.ToString(dateFormat)); // Add a recipient. Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; // Change the recipient in the next line if necessary. Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(mailTo); oRecip.Resolve(); // Send. oMsg.Send(); // Clean up. oRecip = null; oRecips = null; oMsg = null; oApp = null; Log(string.Format("Email sent sucessfully to {0}", mailTo)); }//end of try block catch { Log($"Email sending failed \n From :{mailFrom} To :{mailTo}"); throw; } //end of catch } //end of Em
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 bool hasWrongAttachmentName(Outlook.Attachment attachment, Outlook.MailItem mailItem) { if (isImageAttachment(attachment)) { return(false); } Outlook.Recipients recips = mailItem.Recipients; foreach (Outlook.Recipient recip in recips) { string recipMail = recip.PropertyAccessor.GetProperty(Constants.PR_SMTP_ADDRESS).ToString(); string recipDomain = recipMail.Split('@')[1]; // 例外判斷:網域白名單不檢查 if (Constants.IgnoredEncryptionCheckWhiteList.Contains(recipDomain, StringComparer.OrdinalIgnoreCase)) { continue; } string fileName = Path.GetFileNameWithoutExtension(attachment.FileName); // NXXX_XXXX_Q_1210 string[] splitFileName = fileName.Split('_'); string currentDate = DateTime.Now.ToString("MMdd"); // 1231 if (splitFileName.Length != 4) { return(true); } // N if (!Constants.ProjectCapital.Contains(splitFileName[0][0].ToString())) { return(true); } // Q if (!Constants.ProjectFixedAlphabet.Contains(splitFileName[2].ToString())) { return(true); } // date if (splitFileName[3].ToString() != currentDate) { return(true); } } return(false); }
static void MailOperations() { Console.WriteLine("Do You want to Compose a Mail with the Same Excel Attachement? Press [Y] for Yes any other key for N"); string input = Console.ReadLine(); if (input.ToLower().Contains("y")) { try { // Create the Outlook application. Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application(); // Create a new mail item. Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); // Set HTMLBody. //add the body of the email var statusDate = StatusDate.ToString("dd MMMM"); oMsg.Subject = "WP Daily Update – Subha Deb - " + statusDate; StringBuilder htmlBody = new StringBuilder(); htmlBody.Append("Hi,<br/> <br/> PFA the Status for " + statusDate); htmlBody.Append("<br/> <br/> Thanks, <br> Subha Deb"); oMsg.HTMLBody = htmlBody.ToString(); //Add an attachment. int iPosition = (int)oMsg.Body.Length + 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; //now attached the file Outlook.Attachment oAttach = oMsg.Attachments.Add(GeneratedExcelFileNamePath, iAttachType, iPosition); // Add a recipient. Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; // Change the recipient in the next line if necessary. foreach (var email in ReceipentsEmailIdsList) { Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(email); oRecip.Resolve(); oRecip = null; } oMsg.Display(true); // Send. //oMsg.Send(); // Clean up. oRecips = null; oMsg = null; oApp = null; }//end of try block catch (Exception ex) { Console.WriteLine("Got Exception"); Console.WriteLine(ex.ToString()); }//end of catch } }
public static int Main(string[] args) { try { // Create the Outlook application by using inline initialization. Outlook.Application oApp = new Outlook.Application(); //Create the new message by using the simplest approach. Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); //Add a recipient. // TODO: Change the following recipient where appropriate. Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("e-mail address"); oRecip.Resolve(); //Set the basic properties. oMsg.Subject = "This is the subject of the test message"; oMsg.Body = "This is the text in the message."; //Add an attachment. // TODO: change file path where appropriate String sSource = "C:\\setupxlg.txt"; String sDisplayName = "MyFirstAttachment"; int iPosition = (int)oMsg.Body.Length + 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; Outlook.Attachment oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName); // If you want to, display the message. // oMsg.Display(true); //modal //Send the message. oMsg.Save(); oMsg.Send(); //Explicitly release objects. oRecip = null; oAttach = null; oMsg = null; oApp = null; } // Simple error handler. catch (Exception e) { Console.WriteLine("{0} Exception caught: ", e); } //Default return value. return(0); }
//SMTP Authentication- Whereby an SMTP client may log in using an authentication mechanism chosen among supported by SMTP servers. public static void smtpMailConfiguration(string htmlBody, string displayName, string subject, string recipientGroup) { try { // Create the Outlook application. Outlook.Application oApp = new Outlook.Application(); // Create a new mail item. Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); // Set HTMLBody. //add the body of the email oMsg.HTMLBody = htmlBody; //Add an attachment. String sDisplayName = displayName; int iPosition = (int)oMsg.Body.Length + 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; string fileName = reportZipath + ".zip"; if (File.Exists(fileName)) { //now attached the file Outlook.Attachment oAttach = oMsg.Attachments.Add (fileName, iAttachType, iPosition, sDisplayName); } else { Logger.log("No HTML Report File Exists"); } //Subject line oMsg.Subject = subject; // Add a recipient. Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; // Change the recipient in the next line if necessary. Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipientGroup); oRecip.Resolve(); // Send. oMsg.Send(); // Clean up. oRecip = null; oRecips = null; oMsg = null; oApp = null; Logger.log("Mail Sent sucessfully"); }//end of try block catch (Exception ex) { Logger.log("Error While Sending Email::" + ex.Message); }//end of catch }
private void sendMessage() { try { // Create the Outlook application by using inline initialization. Outlook.Application oApp = new Outlook.Application(); //Create the new message by using the simplest approach. Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); //Add a recipient. // TODO: Change the following recipient where appropriate. Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("*****@*****.**"); oRecip.Resolve(); //Set the basic properties. oMsg.Subject = "This is the subject of the test message With modal Dialog"; oMsg.Body = "TThis Is When outLook is Closed Testin if it Sends!!!!!!!!!\nversion 34235245"; //Add an attachment. // TODO: change file path where appropriate String sSource = "C:\\Recovery.txt"; String sDisplayName = "MyFirstAttachment"; int iPosition = (int)oMsg.Body.Length + 1; int iAttachType = (int)Outlook.OlAttachmentType.olByValue; Outlook.Attachment oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName); // If you want to, display the message. //oMsg.Display(true); //modal //Send the message. oMsg.Save(); oMsg.Send(); //Explicitly release objects. oRecip = null; oAttach = null; oMsg = null; oApp = null; } // Simple error handler. catch (Exception ex) { MessageBox.Show("error" + ex, ""); //Console.WriteLine("{0} Exception caught: ", ex); } }
// 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; }
//Item "Envoi vers Nuxeo" Attachment public void PacktMenuItem_AttachmentContextMenuDisplay(Microsoft.Office.Core.CommandBar PacktCommandBar, Microsoft.Office.Interop.Outlook.AttachmentSelection Selection) { Office.CommandBarButton PacktCustomItem = (Office.CommandBarButton)PacktCommandBar.Controls.Add(Office.MsoControlType.msoControlButton, Type.Missing, "Custom Menu Item", PacktCommandBar.Controls.Count + 1, Type.Missing); PacktCustomItem.Caption = "Envoi vers Nuxeo..."; attachment = (Outlook.Attachment)Selection[1]; // Set it to visible PacktCustomItem.Visible = true; PacktCustomItem.Click += new Office._CommandBarButtonEvents_ClickEventHandler(AttachmentCustomItem_Click); }
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; }
public MockComparisonInformation(Outlook.Attachment original, Outlook.Attachment modified, string originalEntityId, string modifiedEntityId) : base(original, modified, originalEntityId, modifiedEntityId) { _originalAttachment = original; _modifiedAttachment = modified; }