예제 #1
0
        /// <summary>
        /// A method to retrieve all inspectors which can act as an export target
        /// </summary>
        /// <param name="outlookApplication">IOutlookApplication</param>
        /// <returns>List<string> with inspector captions (window title)</returns>
        private static List <string> RetrievePossibleTargets(IOutlookApplication outlookApplication)
        {
            List <string> possibleTargets = new List <string>();
            Inspectors    inspectors      = outlookApplication.Inspectors;

            if (inspectors != null && inspectors.Count > 0)
            {
                LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count);
                for (int i = 1; i <= inspectors.Count; i++)
                {
                    Inspector inspector = outlookApplication.Inspectors[i];
                    LOG.DebugFormat("Checking inspector '{0}'", inspector.Caption);
                    try {
                        Item currentMail = inspector.CurrentItem;
                        if (currentMail != null && OlObjectClass.olMail.Equals(currentMail.Class))
                        {
                            if (currentMail != null && !currentMail.Sent)
                            {
                                possibleTargets.Add(inspector.Caption);
                            }
                        }
                    } catch (Exception) {
                    }
                }
            }
            return(possibleTargets);
        }
예제 #2
0
 /// <summary>
 /// Initialize static outlook variables like version and currentuser
 /// </summary>
 /// <param name="outlookApplication"></param>
 private static void InitializeVariables(IOutlookApplication outlookApplication)
 {
     if (outlookApplication == null || outlookVersion != null)
     {
         return;
     }
     try {
         outlookVersion = new Version(outlookApplication.Version);
         LOG.InfoFormat("Using Outlook {0}", outlookVersion);
     } catch (Exception exVersion) {
         LOG.Error(exVersion);
         LOG.Warn("Assuming outlook version 1.");
         outlookVersion = new Version(1, 1, 1, 1);
     }
     // Preventing retrieval of currentUser if Outlook is older than 2007
     if (outlookVersion.Major >= OUTLOOK_2007)
     {
         try {
             INameSpace mapiNamespace = outlookApplication.GetNameSpace("MAPI");
             currentUser = mapiNamespace.CurrentUser.Name;
             LOG.InfoFormat("Current user: {0}", currentUser);
         } catch (Exception exNS) {
             LOG.Error(exNS);
         }
     }
 }
예제 #3
0
 /// <summary>
 /// Initialize static outlook variables like version and currentuser
 /// </summary>
 /// <param name="outlookApplication"></param>
 private static void InitializeVariables(IOutlookApplication outlookApplication)
 {
     if (outlookApplication == null || _outlookVersion != null)
     {
         return;
     }
     try {
         _outlookVersion = new Version(outlookApplication.Version);
         Log.InfoFormat("Using Outlook {0}", _outlookVersion);
     } catch (Exception exVersion) {
         Log.Error(exVersion);
         Log.Warn("Assuming outlook version 1997.");
         _outlookVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0);
     }
     // Preventing retrieval of currentUser if Outlook is older than 2007
     if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007)
     {
         try {
             INameSpace mapiNamespace = outlookApplication.GetNameSpace("MAPI");
             _currentUser = mapiNamespace.CurrentUser.Name;
             Log.InfoFormat("Current user: {0}", _currentUser);
         } catch (Exception exNs) {
             Log.Error(exNs);
         }
     }
 }
예제 #4
0
        /// <summary>
        /// Call this to get the running outlook application, or create a new instance
        /// </summary>
        /// <returns>IOutlookApplication</returns>
        private static IOutlookApplication GetOrCreateOutlookApplication()
        {
            IOutlookApplication outlookApplication = COMWrapper.GetOrCreateInstance <IOutlookApplication>();

            InitializeVariables(outlookApplication);
            return(outlookApplication);
        }
예제 #5
0
        /// <summary>
        /// A method to retrieve all inspectors which can act as an export target
        /// </summary>
        /// <param name="allowMeetingAsTarget">bool true if also exporting to meetings</param>
        /// <returns>List<string> with inspector captions (window title)</returns>
        public static Dictionary <string, OlObjectClass> RetrievePossibleTargets(bool allowMeetingAsTarget)
        {
            Dictionary <string, OlObjectClass> inspectorCaptions = new Dictionary <string, OlObjectClass>();

            try {
                using (IOutlookApplication outlookApplication = GetOutlookApplication()) {
                    if (outlookApplication == null)
                    {
                        return(null);
                    }

                    using (Inspectors inspectors = outlookApplication.Inspectors) {
                        if (inspectors != null && inspectors.Count > 0)
                        {
                            for (int i = 1; i <= inspectors.Count; i++)
                            {
                                using (Inspector inspector = outlookApplication.Inspectors[i]) {
                                    string inspectorCaption = inspector.Caption;
                                    using (Item currentItem = inspector.CurrentItem) {
                                        if (canExportToInspector(currentItem, allowMeetingAsTarget))
                                        {
                                            OlObjectClass currentItemClass = currentItem.Class;
                                            inspectorCaptions.Add(inspector.Caption, currentItemClass);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                LOG.Warn("Problem retrieving word destinations, ignoring: ", ex);
            }
            return(inspectorCaptions);
        }
        /// <summary>
        /// Export the image stored in tmpFile to the Inspector with the caption
        /// </summary>
        /// <param name="inspectorCaption">Caption of the inspector</param>
        /// <param name="tmpFile">Path to image file</param>
        /// <param name="attachmentName">name of the attachment (used as the tooltip of the image)</param>
        /// <returns>true if it worked</returns>
        public static bool ExportToInspector(string inspectorCaption, string tmpFile, string attachmentName)
        {
            // Assume true, although this might cause issues.
            bool allowMeetingAsTarget = true;

            using (IOutlookApplication outlookApplication = GetOrCreateOutlookApplication()) {
                if (outlookApplication != null)
                {
                    Inspectors inspectors = outlookApplication.Inspectors;
                    if (inspectors != null && inspectors.Count > 0)
                    {
                        LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count);
                        for (int i = 1; i <= inspectors.Count; i++)
                        {
                            Inspector inspector      = outlookApplication.Inspectors[i];
                            string    currentCaption = inspector.Caption;
                            if (currentCaption.StartsWith(inspectorCaption))
                            {
                                if (canExportToInspector(inspector, allowMeetingAsTarget))
                                {
                                    try {
                                        return(ExportToInspector(inspector, tmpFile, attachmentName));
                                    } catch (Exception exExport) {
                                        LOG.Error("Export to " + currentCaption + " failed.", exExport);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
            public void Init(IOutlookApplication application, IMailItem mailItem)
            {
                this._application = application;
                this.mailItem     = mailItem;
                String accountAddress = application.GetPrimarySmtpAddresses().FirstOrDefault() ?? "";



                //PPOLService.PsnNoteAPIService local = new PPOLService.PsnNoteAPIService();
                this.body    = mailItem.HTMLBody;
                this.subject = mailItem.Subject;
                var mItem = mailItem;

                if (mItem.SenderEmailAddress != null && !mItem.SenderEmailAddress.Equals(""))
                {
                    if (mItem.Sent)
                    {
                        fromName = mItem.SenderEmailAddress;
                        //   string fromAddr = "";

                        if (!fromName.Contains('@'))
                        {
                            string findAddress = "";
                            foreach (var contact in _application.FindContactsByEmailDisplayName(fromName))
                            {
                                using (contact)
                                {
                                    foreach (var emailAddress in contact.EmailAddresses)
                                    {
                                        findAddress = emailAddress;
                                        if (!string.IsNullOrEmpty(findAddress))
                                        {
                                            break;
                                        }
                                    }
                                }
                                if (!string.IsNullOrEmpty(findAddress))
                                {
                                    break;
                                }
                            }
                            fromName = findAddress;
                        }
                    }
                    else
                    {
                        fromName = mItem.GetRecipientAddresses().FirstOrDefault();
                    }
                    bccAddressList = accountAddress + "$" + fromName;
                }
                else
                {
                    bccAddressList = accountAddress;
                }
                //      MessageBox.Show(String.Format(bccAddressList));
                toAddress = string.Join(";", mItem.GetRecipientAddresses());
            }
예제 #8
0
        private static IOutlookApplication OutlookApplication()
        {
            IOutlookApplication outlookApplication = (IOutlookApplication)COMWrapper.GetOrCreateInstance(typeof(IOutlookApplication));

            try {
                outlookVersion = new Version(outlookApplication.Version);
            } catch {
            }
            return(outlookApplication);
        }
        /// <summary>
        /// A method to retrieve all inspectors which can act as an export target
        /// </summary>
        /// <returns>List<string> with inspector captions (window title)</returns>
        public static IDictionary <string, OlObjectClass> RetrievePossibleTargets()
        {
            IDictionary <string, OlObjectClass> inspectorCaptions = new SortedDictionary <string, OlObjectClass>();

            try {
                using (IOutlookApplication outlookApplication = GetOutlookApplication()) {
                    if (outlookApplication == null)
                    {
                        return(null);
                    }

                    if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013)
                    {
                        // Check inline "panel" for Outlook 2013
                        using (var activeExplorer = outlookApplication.ActiveExplorer()) {
                            if (activeExplorer != null)
                            {
                                using (var inlineResponse = activeExplorer.ActiveInlineResponse) {
                                    if (canExportToInspector(inlineResponse))
                                    {
                                        OlObjectClass currentItemClass = inlineResponse.Class;
                                        inspectorCaptions.Add(activeExplorer.Caption, currentItemClass);
                                    }
                                }
                            }
                        }
                    }

                    using (IInspectors inspectors = outlookApplication.Inspectors) {
                        if (inspectors != null && inspectors.Count > 0)
                        {
                            for (int i = 1; i <= inspectors.Count; i++)
                            {
                                using (IInspector inspector = outlookApplication.Inspectors[i]) {
                                    string inspectorCaption = inspector.Caption;
                                    using (IItem currentItem = inspector.CurrentItem) {
                                        if (canExportToInspector(currentItem))
                                        {
                                            OlObjectClass currentItemClass = currentItem.Class;
                                            inspectorCaptions.Add(inspector.Caption, currentItemClass);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                LOG.Warn("Problem retrieving word destinations, ignoring: ", ex);
            }
            return(inspectorCaptions);
        }
예제 #10
0
        /// <summary>
        /// Helper method to create an outlook mail item with attachment
        /// </summary>
        /// <param name="tmpfile">The file to send, do not delete the file right away!</param>
        /// <returns>true if it worked, false if not</returns>
        public static bool ExportToOutlook(EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string CC, string BCC, string url)
        {
            bool exported = false;

            try {
                using (IOutlookApplication outlookApplication = GetOrCreateOutlookApplication()) {
                    if (outlookApplication != null)
                    {
                        ExportToNewEmail(outlookApplication, format, tmpFile, subject, attachmentName, to, CC, BCC, url);
                        exported = true;
                    }
                }
                return(exported);
            } catch (Exception e) {
                LOG.Error("Error while creating an outlook mail item: ", e);
            }
            return(exported);
        }
예제 #11
0
        /// <summary>
        /// Export to currently opened Email
        /// </summary>
        /// <param name="activeInspector"></param>
        private static bool ExportToOpenEmail(IOutlookApplication outlookApplication, string tmpFile, string subject)
        {
            using (Inspector activeInspector = outlookApplication.ActiveInspector()) {
                if (activeInspector != null)
                {
                    try {
                        LOG.DebugFormat("Checking active inspector '{0}'", activeInspector.Caption);
                        if (ExportToInspector(activeInspector, tmpFile, subject))
                        {
                            return(true);
                        }
                    } catch (Exception ex) {
                        LOG.DebugFormat("Problem exporting to activeinspector: {0}", ex.Message);
                    }
                }
            }
            Inspectors inspectors = outlookApplication.Inspectors;

            if (inspectors != null && inspectors.Count > 0)
            {
                LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count);
                for (int i = 1; i <= inspectors.Count; i++)
                {
                    Inspector inspector = outlookApplication.Inspectors[i];
                    LOG.DebugFormat("Checking inspector '{0}'", inspector.Caption);
                    try {
                        bool exported = ExportToInspector(inspector, tmpFile, subject);
                        if (exported)
                        {
                            return(true);
                        }
                    } catch (Exception ex) {
                        LOG.DebugFormat("Problem exporting to inspector: {0}", ex.Message);
                    }
                }
            }

            return(false);
        }
예제 #12
0
        /// <summary>
        /// Helper method to create the outlook mail item with attachment
        /// </summary>
        /// <param name="tmpfile">The file to send</param>
        /// <returns>true if it worked, false if not</returns>
        public static bool ExportToOutlook(string tmpFile, ICaptureDetails captureDetails)
        {
            try {
                bool exported = false;

                // Create a subject for the image
                string subject = captureDetails.Title;
                if (!string.IsNullOrEmpty(subject))
                {
                    subject = subject.Trim();
                }
                // Set default if non is set
                if (string.IsNullOrEmpty(subject))
                {
                    subject = "Greenshot Capture";
                }
                // Make sure it's "clean" so it doesn't corrupt the header
                subject = Regex.Replace(subject, @"[^\x20\d\w]", "");
                using (IOutlookApplication outlookApplication = OutlookApplication()) {
                    if (outlookApplication != null)
                    {
                        exported = ExportToMail(outlookApplication, tmpFile, subject);
                    }
                }
                if (exported)
                {
                    // Wait to make sure the system "imported" the file
                    // TODO: this should be handled differently some time
                    Thread.Sleep(600);
                }
                LOG.DebugFormat("Deleting {0}", tmpFile);
                File.Delete(tmpFile);
                return(exported);
            } catch (Exception e) {
                LOG.Error("Error while creating an outlook mail item: ", e);
            }
            return(false);
        }
예제 #13
0
        private static bool ExportToMail(IOutlookApplication outlookApplication, string tmpFile, string subject)
        {
            bool exported = false;

            if (outlookApplication != null)
            {
                if (conf.OutputOutlookMethod == EmailExport.TryOpenElseNew)
                {
                    LOG.Debug("EmailExport.TryOpenElseNew");
                    try {
                        exported = ExportToOpenEmail(outlookApplication, tmpFile, subject);
                    } catch (Exception ex) {
                        LOG.Error(ex);
                    }
                }
                if (!exported)
                {
                    LOG.Debug("EmailExport.AllwaysNew");
                    ExportToNewEmail(outlookApplication, tmpFile, subject);
                    exported = true;
                }
            }
            return(exported);
        }
예제 #14
0
		/// <summary>
		/// Initialize static outlook variables like version and currentuser
		/// </summary>
		/// <param name="outlookApplication"></param>
		private static void InitializeVariables(IOutlookApplication outlookApplication) {
			if (outlookApplication == null || outlookVersion != null) {
				return;
			}
			try {
				outlookVersion = new Version(outlookApplication.Version);
				LOG.InfoFormat("Using Outlook {0}", outlookVersion);
			} catch (Exception exVersion) {
				LOG.Error(exVersion);
				LOG.Warn("Assuming outlook version 1997.");
				outlookVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0);
			}
			// Preventing retrieval of currentUser if Outlook is older than 2007
			if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
				try {
					INameSpace mapiNamespace = outlookApplication.GetNameSpace("MAPI");
					currentUser = mapiNamespace.CurrentUser.Name;
					LOG.InfoFormat("Current user: {0}", currentUser);
				} catch (Exception exNS) {
					LOG.Error(exNS);
				}
			}
		}
예제 #15
0
		/// <summary>
		/// Export image to a new email
		/// </summary>
		/// <param name="outlookApplication"></param>
		/// <param name="tmpFile"></param>
		/// <param name="captureDetails"></param>
		private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string CC, string BCC, string url) {
			using (IItem newItem = outlookApplication.CreateItem(OlItemType.olMailItem)) {
				if (newItem == null) {
					return;
				}
				//MailItem newMail = COMWrapper.Cast<MailItem>(newItem);
				MailItem newMail = (MailItem)newItem;
				newMail.Subject = subject;
				if (!string.IsNullOrEmpty(to)) {
					newMail.To = to;
				}
				if (!string.IsNullOrEmpty(CC)) {
					newMail.CC = CC;
				}
				if (!string.IsNullOrEmpty(BCC)) {
					newMail.BCC = BCC;
				}
				newMail.BodyFormat = OlBodyFormat.olFormatHTML;
				string bodyString = null;
				// Read the default signature, if nothing found use empty email
				try {
					bodyString = GetOutlookSignature(format);
				} catch (Exception e) {
					LOG.Error("Problem reading signature!", e);
				}
				switch (format) {
					case EmailFormat.Text:
						// Create the attachment (and dispose the COM object after using)
						using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName)) {
							newMail.BodyFormat = OlBodyFormat.olFormatPlain;
							if (bodyString == null) {
								bodyString = "";
							}
							newMail.Body = bodyString;
						}
						break;
					case EmailFormat.HTML:
					default:
						string contentID = Path.GetFileName(tmpFile);
						// Create the attachment (and dispose the COM object after using)
						using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) {
							// add content ID to the attachment
							if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
								try {
									contentID = Guid.NewGuid().ToString();
									IPropertyAccessor propertyAccessor = attachment.PropertyAccessor;
									propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
								} catch {
									LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
									contentID = Path.GetFileName(tmpFile);
								}
							}
						}

						newMail.BodyFormat = OlBodyFormat.olFormatHTML;
						string href = "";
						string hrefEnd = "";
						if (!string.IsNullOrEmpty(url)) {
							href = string.Format("<A HREF=\"{0}\">", url);
							hrefEnd = "</A>";
						}
						string htmlImgEmbedded = string.Format("<BR/>{0}<IMG border=0 hspace=0 alt=\"{1}\" align=baseline src=\"cid:{2}\">{3}<BR/>", href, attachmentName, contentID, hrefEnd);
						string fallbackBody = string.Format("<HTML><BODY>{0}</BODY></HTML>", htmlImgEmbedded);
						if (bodyString == null) {
							bodyString = fallbackBody;
						} else {
							int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
							if (bodyIndex >= 0) {
								bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
								if (bodyIndex >= 0) {
									bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
								} else {
									bodyString = fallbackBody;
								}
							} else {
								bodyString = fallbackBody;
							}
						}
						newMail.HTMLBody = bodyString;
						break;
				}
				// So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
				newMail.Display(false);

				using (IInspector inspector = newMail.GetInspector()) {
					if (inspector != null) {
						try {
							inspector.Activate();
						} catch {
							// Ignore
						}
					}
				}
			}
		}
 public EmailAttachProcessor(IOutlookApplication application)
 {
     _application = application;
 }
예제 #17
0
 private static bool ExportToMail(IOutlookApplication outlookApplication, string tmpFile, string subject)
 {
     bool exported = false;
     if (outlookApplication != null) {
         if (conf.OutputOutlookMethod == EmailExport.TryOpenElseNew) {
             LOG.Debug("EmailExport.TryOpenElseNew");
             try {
                 exported = ExportToOpenEmail(outlookApplication, tmpFile, subject);
             } catch (Exception ex) {
                 LOG.Error(ex);
             }
         }
         if (!exported) {
             LOG.Debug("EmailExport.AllwaysNew");
             ExportToNewEmail(outlookApplication, tmpFile, subject);
             exported = true;
         }
     }
     return exported;
 }
예제 #18
0
        /// <summary>
        /// Export image to a new email
        /// </summary>
        /// <param name="outlookApplication"></param>
        /// <param name="tmpFile"></param>
        /// <param name="captureDetails"></param>
        private static void ExportToNewEmail(IOutlookApplication outlookApplication, string tmpFile, string subject)
        {
            Item newMail = outlookApplication.CreateItem( OlItemType.olMailItem );
            if (newMail == null) {
                return;
            }
            newMail.Subject = subject;
            newMail.BodyFormat = OlBodyFormat.olFormatHTML;
            string bodyString = null;
            // Read the default signature, if nothing found use empty email
            try {
                bodyString = GetOutlookSignature();
            } catch (Exception e) {
                LOG.Error("Problem reading signature!", e);
            }
            switch(conf.OutputEMailFormat) {
                case EmailFormat.OUTLOOK_TXT:
                    newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, subject);
                    newMail.BodyFormat = OlBodyFormat.olFormatPlain;
                    if (bodyString == null) {
                        bodyString = "";
                    }
                    newMail.Body = bodyString;
                    break;
                case EmailFormat.OUTLOOK_HTML:
                default:
                    // Create the attachment
                    Attachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, subject);
                    // add content ID to the attachment
                    string contentID = Path.GetFileName(tmpFile);
                    if (outlookVersion.Major >=12) {
                        // Add the content id to the attachment
                        try {
                            contentID = Guid.NewGuid().ToString();
                            PropertyAccessor propertyAccessor = attachment.PropertyAccessor;
                            propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
                        } catch {
                            LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
                            contentID = Path.GetFileName(tmpFile);
                        }
                    }

                    newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                    string htmlImgEmbedded = "<BR/><IMG border=0 hspace=0 alt=\"" + subject + "\" align=baseline src=\"cid:"+ contentID +"\"><BR/>";
                    string fallbackBody = "<HTML><BODY>" + htmlImgEmbedded + "</BODY></HTML>";
                    if (bodyString == null) {
                        bodyString = fallbackBody;
                    } else {
                        int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
                        if (bodyIndex >= 0) {
                            bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
                            if (bodyIndex >= 0) {
                                bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
                            } else {
                                bodyString = fallbackBody;
                            }
                        } else {
                            bodyString = fallbackBody;
                        }
                    }
                    newMail.HTMLBody = bodyString;
                    break;
            }
            // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
            newMail.Display(false);
        }
예제 #19
0
        /// <summary>
        /// Export to currently opened Email
        /// </summary>
        /// <param name="activeInspector"></param>
        private static bool ExportToOpenEmail(IOutlookApplication outlookApplication, string tmpFile, string subject)
        {
            using (Inspector activeInspector = outlookApplication.ActiveInspector()) {
                if (activeInspector != null) {
                    try {
                        LOG.DebugFormat("Checking active inspector '{0}'", activeInspector.Caption);
                        if (ExportToInspector(activeInspector, tmpFile, subject)) {
                            return true;
                        }
                    } catch (Exception ex) {
                        LOG.DebugFormat("Problem exporting to activeinspector: {0}", ex.Message);
                    }
                }
            }
            Inspectors inspectors = outlookApplication.Inspectors;
            if (inspectors != null && inspectors.Count > 0) {
                LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count);
                for(int i=1; i <= inspectors.Count; i++) {
                    Inspector inspector = outlookApplication.Inspectors[i];
                    LOG.DebugFormat("Checking inspector '{0}'", inspector.Caption);
                    try {
                        bool exported = ExportToInspector(inspector, tmpFile, subject);
                        if (exported) {
                            return true;
                        }
                    } catch (Exception ex) {
                        LOG.DebugFormat("Problem exporting to inspector: {0}", ex.Message);
                    }

                }
            }

            return false;
        }
예제 #20
0
        /// <summary>
        /// Export image to a new email
        /// </summary>
        /// <param name="outlookApplication"></param>
        /// <param name="tmpFile"></param>
        /// <param name="captureDetails"></param>
        private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string CC, string BCC, string url)
        {
            Item newItem = outlookApplication.CreateItem(OlItemType.olMailItem);

            if (newItem == null)
            {
                return;
            }
            //MailItem newMail = COMWrapper.Cast<MailItem>(newItem);
            MailItem newMail = (MailItem)newItem;

            newMail.Subject = subject;
            if (!string.IsNullOrEmpty(to))
            {
                newMail.To = to;
            }
            if (!string.IsNullOrEmpty(CC))
            {
                newMail.CC = CC;
            }
            if (!string.IsNullOrEmpty(BCC))
            {
                newMail.BCC = BCC;
            }
            newMail.BodyFormat = OlBodyFormat.olFormatHTML;
            string bodyString = null;

            // If enabled, read the default signature (if nothing found use empty email)
            if (officeConfiguration.OutlookIncludeDefaultSignature)
            {
                try {
                    bodyString = GetOutlookSignature(format);
                } catch (Exception e) {
                    LOG.Error("Problem reading signature!", e);
                }
            }
            switch (format)
            {
            case EmailFormat.Text:
                newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName);
                newMail.BodyFormat = OlBodyFormat.olFormatPlain;
                if (bodyString == null)
                {
                    bodyString = "";
                }
                newMail.Body = bodyString;
                break;

            case EmailFormat.HTML:
            default:
                string contentID = Path.GetFileName(tmpFile);
                // Create the attachment
                using (Attachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) {
                    // add content ID to the attachment
                    if (outlookVersion.Major >= OUTLOOK_2007)
                    {
                        try {
                            contentID = Guid.NewGuid().ToString();
                            PropertyAccessor propertyAccessor = attachment.PropertyAccessor;
                            propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
                        } catch {
                            LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
                            contentID = Path.GetFileName(tmpFile);
                        }
                    }
                }

                newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                string href    = "";
                string hrefEnd = "";
                if (!string.IsNullOrEmpty(url))
                {
                    href    = string.Format("<A HREF=\"{0}\">", url);
                    hrefEnd = "</A>";
                }
                string htmlImgEmbedded = string.Format("<BR/>{0}<IMG border=0 hspace=0 alt=\"{1}\" align=baseline src=\"cid:{2}\">{3}<BR/>", href, attachmentName, contentID, hrefEnd);
                string fallbackBody    = string.Format("<HTML><BODY>{0}</BODY></HTML>", htmlImgEmbedded);
                if (bodyString == null)
                {
                    bodyString = fallbackBody;
                }
                else
                {
                    int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
                    if (bodyIndex >= 0)
                    {
                        bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
                        if (bodyIndex >= 0)
                        {
                            bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
                        }
                        else
                        {
                            bodyString = fallbackBody;
                        }
                    }
                    else
                    {
                        bodyString = fallbackBody;
                    }
                }
                newMail.HTMLBody = bodyString;
                break;
            }
            // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
            newMail.Display(false);
            newMail.GetInspector().Activate();

            if (newItem != null)
            {
                newItem.Dispose();
            }
        }
예제 #21
0
 /// <summary>
 /// A method to retrieve all inspectors which can act as an export target
 /// </summary>
 /// <param name="outlookApplication">IOutlookApplication</param>
 /// <returns>List<string> with inspector captions (window title)</returns>
 private static List<string> RetrievePossibleTargets(IOutlookApplication outlookApplication)
 {
     List<string> possibleTargets = new List<string>();
     Inspectors inspectors = outlookApplication.Inspectors;
     if (inspectors != null && inspectors.Count > 0) {
         LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count);
         for(int i=1; i <= inspectors.Count; i++) {
             Inspector inspector = outlookApplication.Inspectors[i];
             LOG.DebugFormat("Checking inspector '{0}'", inspector.Caption);
             try {
                 Item currentMail = inspector.CurrentItem;
                 if (currentMail != null && OlObjectClass.olMail.Equals(currentMail.Class) ) {
                     if (currentMail != null && !currentMail.Sent) {
                         possibleTargets.Add(inspector.Caption);
                     }
                 }
             } catch (Exception) {
             }
         }
     }
     return possibleTargets;
 }
        /// <summary>
        /// Export the image stored in tmpFile to the Inspector with the caption
        /// </summary>
        /// <param name="inspectorCaption">Caption of the inspector</param>
        /// <param name="tmpFile">Path to image file</param>
        /// <param name="attachmentName">name of the attachment (used as the tooltip of the image)</param>
        /// <returns>true if it worked</returns>
        public static bool ExportToInspector(string inspectorCaption, string tmpFile, string attachmentName)
        {
            using (IOutlookApplication outlookApplication = GetOrCreateOutlookApplication()) {
                if (outlookApplication == null)
                {
                    return(false);
                }
                if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013)
                {
                    // Check inline "panel" for Outlook 2013
                    using (var activeExplorer = outlookApplication.ActiveExplorer()) {
                        if (activeExplorer == null)
                        {
                            return(false);
                        }
                        var currentCaption = activeExplorer.Caption;
                        if (currentCaption.StartsWith(inspectorCaption))
                        {
                            using (var inlineResponse = activeExplorer.ActiveInlineResponse) {
                                using (IItem currentItem = activeExplorer.ActiveInlineResponse) {
                                    if (canExportToInspector(inlineResponse))
                                    {
                                        try {
                                            return(ExportToInspector(activeExplorer, currentItem, tmpFile, attachmentName));
                                        } catch (Exception exExport) {
                                            LOG.Error("Export to " + currentCaption + " failed.", exExport);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                using (IInspectors inspectors = outlookApplication.Inspectors) {
                    if (inspectors == null || inspectors.Count == 0)
                    {
                        return(false);
                    }
                    LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count);
                    for (int i = 1; i <= inspectors.Count; i++)
                    {
                        using (IInspector inspector = outlookApplication.Inspectors[i]) {
                            string currentCaption = inspector.Caption;
                            if (currentCaption.StartsWith(inspectorCaption))
                            {
                                using (IItem currentItem = inspector.CurrentItem) {
                                    if (canExportToInspector(currentItem))
                                    {
                                        try {
                                            return(ExportToInspector(inspector, currentItem, tmpFile, attachmentName));
                                        } catch (Exception exExport) {
                                            LOG.Error("Export to " + currentCaption + " failed.", exExport);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
        /// <summary>
        /// Export image to a new email
        /// </summary>
        /// <param name="outlookApplication"></param>
        /// <param name="tmpFile"></param>
        /// <param name="captureDetails"></param>
        private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName)
        {
            Item newItem = outlookApplication.CreateItem(OlItemType.olMailItem);
            if (newItem == null) {
                return;
            }
            //MailItem newMail = COMWrapper.Cast<MailItem>(newItem);
            MailItem newMail = (MailItem)newItem;
            newMail.Subject = subject;
            newMail.BodyFormat = OlBodyFormat.olFormatHTML;
            string bodyString = null;
            // Read the default signature, if nothing found use empty email
            try {
                bodyString = GetOutlookSignature(format);
            } catch (Exception e) {
                LOG.Error("Problem reading signature!", e);
            }
            switch (format) {
                case EmailFormat.Text:
                    newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName);
                    newMail.BodyFormat = OlBodyFormat.olFormatPlain;
                    if (bodyString == null) {
                        bodyString = "";
                    }
                    newMail.Body = bodyString;
                    break;
                case EmailFormat.HTML:
                default:
                    // Create the attachment
                    Attachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName);
                    // add content ID to the attachment
                    string contentID = Path.GetFileName(tmpFile);
                    if (outlookVersion.Major >= 12) {
                        // Add the content id to the attachment
                        try {
                            contentID = Guid.NewGuid().ToString();
                            PropertyAccessor propertyAccessor = attachment.PropertyAccessor;
                            propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
                        } catch {
                            LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
                            contentID = Path.GetFileName(tmpFile);
                        }
                    }

                    newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                    string htmlImgEmbedded = "<BR/><IMG border=0 hspace=0 alt=\"" + attachmentName + "\" align=baseline src=\"cid:" + contentID + "\"><BR/>";
                    string fallbackBody = "<HTML><BODY>" + htmlImgEmbedded + "</BODY></HTML>";
                    if (bodyString == null) {
                        bodyString = fallbackBody;
                    } else {
                        int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
                        if (bodyIndex >= 0) {
                            bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
                            if (bodyIndex >= 0) {
                                bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
                            } else {
                                bodyString = fallbackBody;
                            }
                        } else {
                            bodyString = fallbackBody;
                        }
                    }
                    newMail.HTMLBody = bodyString;
                    break;
            }
            // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
            try {
                newMail.Display(false);
                newMail.GetInspector().Activate();
            } catch (Exception ex) {
                LOG.WarnFormat("Problem displaying the new email, retrying to display it. Problem: {0}", ex.Message);
                Thread retryDisplayEmail = new Thread(delegate() {
                    int retries = 60;
                    int retryInXSeconds = 5;
                    while (retries-- > 0) {
                        Thread.Sleep(retryInXSeconds * 1000);
                        try {
                            newMail.Display(false);
                            newMail.GetInspector().Activate();
                            LOG.InfoFormat("Managed to display the message.");
                            return;
                        } catch (Exception) {
                            LOG.WarnFormat("Retrying to show email in {0} seconds... Retries left: {1}", retryInXSeconds, retries);
                        }
                    }
                    LOG.WarnFormat("Retry failed, saving message to draft.");
                    newMail.Save();
                });
                retryDisplayEmail.Name = "Retry to display email";
                retryDisplayEmail.IsBackground = true;
                retryDisplayEmail.Start();
            }
        }
예제 #24
0
        /// <summary>
        /// Export image to a new email
        /// </summary>
        /// <param name="outlookApplication"></param>
        /// <param name="format"></param>
        /// <param name="tmpFile"></param>
        /// <param name="subject"></param>
        /// <param name="attachmentName"></param>
        /// <param name="to"></param>
        /// <param name="cc"></param>
        /// <param name="bcc"></param>
        /// <param name="url"></param>
        private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string cc, string bcc, string url)
        {
            using (IItem newItem = outlookApplication.CreateItem(OlItemType.olMailItem)) {
                if (newItem == null)
                {
                    return;
                }
                //MailItem newMail = COMWrapper.Cast<MailItem>(newItem);
                MailItem newMail = (MailItem)newItem;
                newMail.Subject = subject;
                if (!string.IsNullOrEmpty(to))
                {
                    newMail.To = to;
                }
                if (!string.IsNullOrEmpty(cc))
                {
                    newMail.CC = cc;
                }
                if (!string.IsNullOrEmpty(bcc))
                {
                    newMail.BCC = bcc;
                }
                newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                string bodyString = null;
                // Read the default signature, if nothing found use empty email
                try {
                    bodyString = GetOutlookSignature(format);
                } catch (Exception e) {
                    Log.Error("Problem reading signature!", e);
                }
                switch (format)
                {
                case EmailFormat.Text:
                    // Create the attachment (and dispose the COM object after using)
                    using (newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName))
                    {
                        newMail.BodyFormat = OlBodyFormat.olFormatPlain;
                        if (bodyString == null)
                        {
                            bodyString = "";
                        }
                        newMail.Body = bodyString;
                    }
                    break;

                default:
                    string contentId = Path.GetFileName(tmpFile);
                    // Create the attachment (and dispose the COM object after using)
                    using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) {
                        // add content ID to the attachment
                        if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007)
                        {
                            try {
                                contentId = Guid.NewGuid().ToString();
                                IPropertyAccessor propertyAccessor = attachment.PropertyAccessor;
                                propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentId);
                            } catch {
                                Log.Info("Error working with the PropertyAccessor, using filename as contentid");
                                contentId = Path.GetFileName(tmpFile);
                            }
                        }
                    }

                    newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                    string href    = "";
                    string hrefEnd = "";
                    if (!string.IsNullOrEmpty(url))
                    {
                        href    = $"<A HREF=\"{url}\">";
                        hrefEnd = "</A>";
                    }
                    string htmlImgEmbedded = $"<BR/>{href}<IMG border=0 hspace=0 alt=\"{attachmentName}\" align=baseline src=\"cid:{contentId}\">{hrefEnd}<BR/>";
                    string fallbackBody    = $"<HTML><BODY>{htmlImgEmbedded}</BODY></HTML>";
                    if (bodyString == null)
                    {
                        bodyString = fallbackBody;
                    }
                    else
                    {
                        int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
                        if (bodyIndex >= 0)
                        {
                            bodyIndex  = bodyString.IndexOf(">", bodyIndex, StringComparison.Ordinal) + 1;
                            bodyString = bodyIndex >= 0 ? bodyString.Insert(bodyIndex, htmlImgEmbedded) : fallbackBody;
                        }
                        else
                        {
                            bodyString = fallbackBody;
                        }
                    }
                    newMail.HTMLBody = bodyString;
                    break;
                }
                // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
                newMail.Display(false);

                using (IInspector inspector = newMail.GetInspector()) {
                    if (inspector != null)
                    {
                        try {
                            inspector.Activate();
                        } catch {
                            // Ignore
                        }
                    }
                }
            }
        }
예제 #25
0
        /// <summary>
        /// Export image to a new email
        /// </summary>
        /// <param name="outlookApplication"></param>
        /// <param name="tmpFile"></param>
        /// <param name="captureDetails"></param>
        private static void ExportToNewEmail(IOutlookApplication outlookApplication, string tmpFile, string subject)
        {
            Item newMail = outlookApplication.CreateItem(OlItemType.olMailItem);

            if (newMail == null)
            {
                return;
            }
            newMail.Subject    = subject;
            newMail.BodyFormat = OlBodyFormat.olFormatHTML;
            string bodyString = null;

            // Read the default signature, if nothing found use empty email
            try {
                bodyString = GetOutlookSignature();
            } catch (Exception e) {
                LOG.Error("Problem reading signature!", e);
            }
            switch (conf.OutputEMailFormat)
            {
            case EmailFormat.OUTLOOK_TXT:
                newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, subject);
                newMail.BodyFormat = OlBodyFormat.olFormatPlain;
                if (bodyString == null)
                {
                    bodyString = "";
                }
                newMail.Body = bodyString;
                break;

            case EmailFormat.OUTLOOK_HTML:
            default:
                // Create the attachment
                Attachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, subject);
                // add content ID to the attachment
                string contentID = Path.GetFileName(tmpFile);
                if (outlookVersion.Major >= 12)
                {
                    // Add the content id to the attachment
                    try {
                        contentID = Guid.NewGuid().ToString();
                        PropertyAccessor propertyAccessor = attachment.PropertyAccessor;
                        propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
                    } catch {
                        LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
                        contentID = Path.GetFileName(tmpFile);
                    }
                }

                newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                string htmlImgEmbedded = "<BR/><IMG border=0 hspace=0 alt=\"" + subject + "\" align=baseline src=\"cid:" + contentID + "\"><BR/>";
                string fallbackBody    = "<HTML><BODY>" + htmlImgEmbedded + "</BODY></HTML>";
                if (bodyString == null)
                {
                    bodyString = fallbackBody;
                }
                else
                {
                    int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
                    if (bodyIndex >= 0)
                    {
                        bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
                        if (bodyIndex >= 0)
                        {
                            bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
                        }
                        else
                        {
                            bodyString = fallbackBody;
                        }
                    }
                    else
                    {
                        bodyString = fallbackBody;
                    }
                }
                newMail.HTMLBody = bodyString;
                break;
            }
            // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
            newMail.Display(false);
        }
        /// <summary>
        /// Export image to a new email
        /// </summary>
        /// <param name="outlookApplication"></param>
        /// <param name="tmpFile"></param>
        /// <param name="captureDetails"></param>
        private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName)
        {
            Item newItem = outlookApplication.CreateItem(OlItemType.olMailItem);

            if (newItem == null)
            {
                return;
            }
            //MailItem newMail = COMWrapper.Cast<MailItem>(newItem);
            MailItem newMail = (MailItem)newItem;

            newMail.Subject    = subject;
            newMail.BodyFormat = OlBodyFormat.olFormatHTML;
            string bodyString = null;

            // Read the default signature, if nothing found use empty email
            try {
                bodyString = GetOutlookSignature(format);
            } catch (Exception e) {
                LOG.Error("Problem reading signature!", e);
            }
            switch (format)
            {
            case EmailFormat.Text:
                newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName);
                newMail.BodyFormat = OlBodyFormat.olFormatPlain;
                if (bodyString == null)
                {
                    bodyString = "";
                }
                newMail.Body = bodyString;
                break;

            case EmailFormat.HTML:
            default:
                // Create the attachment
                Attachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName);
                // add content ID to the attachment
                string contentID = Path.GetFileName(tmpFile);
                if (outlookVersion.Major >= 12)
                {
                    // Add the content id to the attachment
                    try {
                        contentID = Guid.NewGuid().ToString();
                        PropertyAccessor propertyAccessor = attachment.PropertyAccessor;
                        propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
                    } catch {
                        LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
                        contentID = Path.GetFileName(tmpFile);
                    }
                }

                newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                string htmlImgEmbedded = "<BR/><IMG border=0 hspace=0 alt=\"" + attachmentName + "\" align=baseline src=\"cid:" + contentID + "\"><BR/>";
                string fallbackBody    = "<HTML><BODY>" + htmlImgEmbedded + "</BODY></HTML>";
                if (bodyString == null)
                {
                    bodyString = fallbackBody;
                }
                else
                {
                    int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
                    if (bodyIndex >= 0)
                    {
                        bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
                        if (bodyIndex >= 0)
                        {
                            bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
                        }
                        else
                        {
                            bodyString = fallbackBody;
                        }
                    }
                    else
                    {
                        bodyString = fallbackBody;
                    }
                }
                newMail.HTMLBody = bodyString;
                break;
            }
            // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
            try {
                newMail.Display(false);
                newMail.GetInspector().Activate();
            } catch (Exception ex) {
                LOG.WarnFormat("Problem displaying the new email, retrying to display it. Problem: {0}", ex.Message);
                Thread retryDisplayEmail = new Thread(delegate() {
                    int retries         = 60;
                    int retryInXSeconds = 5;
                    while (retries-- > 0)
                    {
                        Thread.Sleep(retryInXSeconds * 1000);
                        try {
                            newMail.Display(false);
                            newMail.GetInspector().Activate();
                            LOG.InfoFormat("Managed to display the message.");
                            return;
                        } catch (Exception) {
                            LOG.WarnFormat("Retrying to show email in {0} seconds... Retries left: {1}", retryInXSeconds, retries);
                        }
                    }
                    LOG.WarnFormat("Retry failed, saving message to draft.");
                    newMail.Save();
                });
                retryDisplayEmail.Name         = "Retry to display email";
                retryDisplayEmail.IsBackground = true;
                retryDisplayEmail.Start();
            }
        }