public static string EmailAddressesStr(Outlook.MailItem email, bool incML = false)
        {
            //find the client from e-mail
            //collect all the email addressess.
            string emails = email.SenderEmailAddress;

            const string PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

            foreach (Outlook.Recipient rec in email.Recipients)
            {
                Outlook.PropertyAccessor pa = rec.PropertyAccessor;
                string s = pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                s = s.ToLower();
                if (!incML)
                {
                    if (!s.Contains("milstedlangdon"))
                    {
                        emails += ";" + pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                    }
                }
            }
            //Remove any unwanted '
            emails = emails.Replace("'", "");
            return(emails);
        }
            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 string GetHeader(Outlook.MailItem item, string headerName)
        {
            Outlook.PropertyAccessor accessor = null;

            try
            {
                accessor = item.PropertyAccessor;
                return(accessor.GetProperty(headerName));
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                Debug.WriteLine("GetHeader: Failed to retreive header, this is expected behaviour when the header is not present: " + ex.ToString());
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine("GetHeader: Unexpected error retrieving header: " + ex.ToString());
            }
            finally
            {
                if (accessor != null)
                {
                    Marshal.ReleaseComObject(accessor);
                }
            }

            return(null);
        }
Beispiel #4
0
        internal static object GetProperty(this Outlook.MailItem _mailItem, string _propertyName)
        {
            if (_mailItem == null)
            {
                throw new ArgumentNullException();
            }

            Outlook.PropertyAccessor propertyAccessor = null;
            try
            {
                propertyAccessor = _mailItem.PropertyAccessor;

                if (propertyAccessor != null)
                {
                    return(propertyAccessor.GetProperty(_propertyName));
                }
            }
            catch (COMException)
            {
            }
            finally
            {
                if (propertyAccessor != null)
                {
                    Marshal.ReleaseComObject(propertyAccessor);
                    propertyAccessor = null;
                }
            }

            return(null);
        }
Beispiel #5
0
        public static string GetMailItemHeaderItem(Outlook.MailItem mailItem, Regex regex)
        {
            if (mailItem == null)
            {
                return(string.Empty);
            }

            string
                TransportMessageHeadersSchema = "http://schemas.microsoft.com/mapi/proptag/0x007D001E",
                header = string.Empty;

            try
            {
                if (mailItem.PropertyAccessor != null)
                {
                    Outlook.PropertyAccessor
                        propertyAccessor = mailItem.PropertyAccessor;

                    header = (string)propertyAccessor.GetProperty(TransportMessageHeadersSchema);
                }

                Match
                    match = regex.Match(header);

                header = match.Success ? match.Value.Trim() : string.Empty;
            }
            catch (Exception eException)
            {
                header = eException.Message;
            }

            return(header);
        }
Beispiel #6
0
        /// <summary>
        /// Finds the Global Address List associated with the MailStore
        /// </summary>
        /// <returns>OLAddressList for GAL or null if store has no GAL</returns>
        public IAddressBook GetGlobalAddressList()
        {
            string PR_EMSMDB_SECTION_UID = @"http://schemas.microsoft.com/mapi/proptag/0x3D150102";

            if (_store == null)
            {
                throw new ArgumentNullException();
            }

            Outlook.PropertyAccessor oPAStore = _store.PropertyAccessor;
            string storeUID = oPAStore.BinaryToString(oPAStore.GetProperty(PR_EMSMDB_SECTION_UID));

            foreach (Outlook.AddressList addrList in _store.Session.AddressLists)
            {
                Outlook.PropertyAccessor oPAAddrList = addrList.PropertyAccessor;
                string addrListUID = oPAAddrList.BinaryToString(oPAAddrList.GetProperty(PR_EMSMDB_SECTION_UID));

                // Returns addrList if match on storeUID
                // and type is olExchangeGlobalAddressList.
                if (addrListUID == storeUID && addrList.AddressListType ==
                    Outlook.OlAddressListType.olExchangeGlobalAddressList)
                {
                    return(new AddressBookProviderOM(addrList));
                }
            }

            return(null);
        }
Beispiel #7
0
        public void Button_Click(Office.IRibbonControl control)
        {
            try
            {
                Outlook.Recipient  recipient  = null;
                Outlook.Recipients recipients = null;

                Outlook.Application application = new Outlook.Application();
                Outlook.Explorer    explorer    = application.ActiveExplorer();
                Outlook.Inspector   inspector   = application.ActiveInspector();
                inspector.Activate();
                Outlook._MailItem mailItem = inspector.CurrentItem;

                //Outlook.Application outlookApplication = new Outlook.Application();
                //Outlook.MailItem mail = (Outlook.MailItem)outlookApplication.ActiveInspector().CurrentItem;

                if (mailItem != null)
                {
                    recipients = mailItem.Recipients;
                    recipients.ResolveAll();
                    String       StrR            = "";
                    const string PR_SMTP_ADDRESS =
                        "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
                    foreach (Outlook.Recipient recip in recipients)
                    {
                        Outlook.PropertyAccessor pa = recip.PropertyAccessor;
                        string smtpAddress          =
                            pa.GetProperty(PR_SMTP_ADDRESS).ToString();

                        string[] strsplit = smtpAddress.Split('@');
                        if (!StrR.Contains(strsplit[1]))
                        {
                            StrR += strsplit[1] + Environment.NewLine;
                        }
                    }
                    if (StrR != string.Empty)
                    {
                        MyMessageBox ObjMyMessageBox = new MyMessageBox();
                        ObjMyMessageBox.ShowBox(StrR);
                    }



                    //recipient.Resolve();
                    //                DialogResult result = MessageBox.Show("Are you sure you want to send emails to the following domains " + StrR, "Varify Domains ",
                    //MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    //                if (result == DialogResult.Yes)
                    //                {
                    //                    //code for Yes
                    //                }
                    //                else
                    //                {

                    //                }
                }
            }
            catch (Exception ex)
            {
            }
        }
        void items_ItemAdd(object Item)
        {
            Outlook.MailItem mail = (Outlook.MailItem)Item;
            try
            {
                MailServiceReference.MailServiceClient mailServiceObj = new MailServiceReference.MailServiceClient();
                if (Item != null)
                {
                    string filterSenderMailID = mailServiceObj.GetTargetMailId();

                    const string       PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
                    Outlook.Recipients recips          = mail.Recipients;
                    foreach (Outlook.Recipient recip in recips)
                    {
                        Outlook.PropertyAccessor pa = recip.PropertyAccessor;
                        string smtpAddress          =
                            pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                        if (smtpAddress.ToLower() == filterSenderMailID.ToLower())
                        {
                            mailServiceObj.InsertMailBody(mail.SenderEmailAddress, mail.ReceivedByName, mail.Subject, mail.Body);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "Claysys UCU Outlook plugging";
                appLog.WriteEntry("Exception : " + ex);
                throw ex;
            }
        }
Beispiel #9
0
        private static void NameSortStores(Outlook.Application OA)
        {
            NameSpace S = OA.Session;

            for (int yrs = 2000; yrs < 2019; yrs++)
            {
                String PST_displayName = String.Format("{0}-00-00", yrs.ToString("0000"));
                Store  St = GetStore(S, PST_displayName);
                if (St == null)
                {
                    continue;
                }
                Folder rF = St.GetRootFolder() as Folder;
                rF.Name = PST_displayName;
                Outlook.PropertyAccessor pA = St.PropertyAccessor;
                dynamic P = pA.GetProperty(@"http://schemas.microsoft.com/mapi/proptag/0x3001001E");

                //pA.SetProperty(@"http://schemas.microsoft.com/mapi/proptag/0x3001001E", PST_displayName);
                rF.ShowItemCount = OlShowItemCount.olShowTotalItemCount;
                Folder a = null;
                if (OutlookFolderExists(rF.Folders, "Inbox"))
                {
                    a = GetFolder(rF, "Inbox");
                }
                else
                {
                    a = rF.Folders.Add("Inbox") as Outlook.Folder;
                }
                CreateMonthSubfolders(a);
            }
        }
Beispiel #10
0
        public static string GetMailHeader(Outlook.PropertyAccessor prop)
        {
            const string PR_TRANSPORT_MESSAGE_HEADERS = "http://schemas.microsoft.com/mapi/proptag/0x007D001E";
            string       headerString = (string)prop.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(prop);

            return(headerString);
        }
Beispiel #11
0
        private void CreateMailItem(Outlook.MailItem selectedItem)
        {
            Outlook.PropertyAccessor olPA = selectedItem.PropertyAccessor;
            string header     = olPA.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS);
            string spamDomain = selectedItem.SenderEmailAddress.Split('@')[1];
            POCO   response   = JsonConvert.DeserializeObject <POCO>(GetAbuseEmail(spamDomain));

            Outlook.MailItem mailItem = (Outlook.MailItem)
                                        Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.Subject    = "Spam Abuse from: " + spamDomain;
            mailItem.To         = response.data["email"];
            mailItem.Body       = GetBody(selectedItem.Body, header, spamDomain);
            mailItem.Importance = Outlook.OlImportance.olImportanceLow;
            mailItem.Display(false);
        }
        private void testForm_Load(object sender, EventArgs e)
        {
            initComoBoxes();
            const string PR_SMTP_ADDRESS =
                "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

            txtMailBody.Text    = mailItem.Body;
            txtMailSybject.Text = mailItem.Subject;
            foreach (Outlook.Recipient recipeint in mailItem.Recipients)
            {
                string smtpAddress = "";

                if (recipeint.AddressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry ||
                    recipeint.AddressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                {
                    Outlook.PropertyAccessor pa = recipeint.PropertyAccessor;
                    smtpAddress = pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                }
                else
                {
                    smtpAddress = recipeint.Address;
                }

                txtRecipient.Text += smtpAddress + ";";
            }
            DateTime creationTime = mailItem.CreationTime;

            txtDateTimeCreated.Text = creationTime.ToString(@"dd.MM.yyy HH:mm:ss");
            //Outlook.PropertyAccessor pa2 =  mailItem.Sender.PropertyAccessor;
            string smtpAddressAuthor = "";

            if (mailItem.Sender.AddressEntryUserType ==
                Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry ||
                mailItem.Sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
            {
                Outlook.ExchangeUser exchUser =
                    mailItem.Sender.GetExchangeUser();
                if (exchUser != null)
                {
                    smtpAddressAuthor = exchUser.PrimarySmtpAddress;
                }
            }
            else
            {
                smtpAddressAuthor = mailItem.Sender.Address;
            }
            txtAuthor.Text = smtpAddressAuthor;
        }
Beispiel #13
0
        /// <summary>
        /// Gets the mail item property
        /// </summary>
        /// <param name="item"></param>
        /// <param name="propName"></param>
        /// <returns></returns>
        private object GetMailItemProperty(Outlook.MailItem item, string propName)
        {
            object value = null;

            try
            {
                Outlook.PropertyAccessor accessor = item.PropertyAccessor;
                value = accessor.GetProperty(propName);
            }
            catch (System.Exception ex)
            {
                //[SF] Don't re-throw any error
                ex.GetType();
            }
            return(value);
        }
Beispiel #14
0
        private void CurrentExplorer_Event()
        {
            Outlook.MAPIFolder selectedFolder =
                this.Application.ActiveExplorer().CurrentFolder;

            String       itemMessage     = null;
            const string PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

            try
            {
                if (this.Application.ActiveExplorer().Selection.Count > 0)
                {
                    Object selObject = this.Application.ActiveExplorer().Selection[1];


                    if (selObject is Outlook.AppointmentItem)
                    {
                        Outlook.AppointmentItem apptItem =
                            (selObject as Outlook.AppointmentItem);

                        Outlook.Recipients recips = apptItem.Recipients;
                        string             str    = null;

                        foreach (Outlook.Recipient recip in recips)
                        {
                            if (recip.MeetingResponseStatus != Outlook.OlResponseStatus.olResponseAccepted)
                            {
                                Outlook.PropertyAccessor pa = recip.PropertyAccessor;
                                string smtpAddress          =
                                    pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                                str += smtpAddress + ";";
                            }
                        }
                        if (str != null)
                        {
                            itemMessage = str;
                            MessageBox.Show("Not responded: " + itemMessage);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #15
0
        private static List <string> GetSMTPAddressForRecipients(Outlook.MailItem mail)
        {
            List <string> recepients      = new List <string>();
            const string  PR_SMTP_ADDRESS =
                "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

            Outlook.Recipients recips = mail.Recipients;
            foreach (Outlook.Recipient recip in recips)
            {
                Outlook.PropertyAccessor pa = recip.PropertyAccessor;
                string smtpAddress          =
                    pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                //stringBuilder.AppendLine(recip.Name + " SMTP=" + smtpAddress);
                recepients.Add(smtpAddress);
            }
            return(recepients);
        }
Beispiel #16
0
        void MailItemHeaderShow(Outlook.MailItem mailItem)
        {
            if (mailItem == null)
            {
                return;
            }

            System.Windows.Forms.TextBox
                tmpTextBox;

            if ((tmpTextBox = myUserControl1.Controls["textBox1"] as System.Windows.Forms.TextBox) != null)
            {
                //http://blogs.msdn.com/b/zainnab/archive/2008/07/01/using-visual-studio-2008-vsto-outlook-to-pull-out-rfc-822-header-data.aspx
                //http://www.lessanvaezi.com/email-headers-from-outlook-mailitem/

                string
                    TransportMessageHeadersSchema = "http://schemas.microsoft.com/mapi/proptag/0x007D001E",
                // TransportMessageHeadersSchema = "http://schemas.microsoft.com/mapi/proptag/0x007D001F", // 4 Unicode
                    header = string.Empty;

                try
                {
                    if (mailItem.PropertyAccessor != null)
                    {
                        Outlook.PropertyAccessor
                            propertyAccessor = mailItem.PropertyAccessor;

                        header = (string)propertyAccessor.GetProperty(TransportMessageHeadersSchema);
                    }

                    Regex
                        r = new Regex("(?<=From:.*?<).*?(?=>)", RegexOptions.Singleline | RegexOptions.IgnoreCase);

                    Match
                        match = r.Match(header);

                    header = match.Success ? match.Value : string.Empty;
                }
                catch (Exception eException)
                {
                    header = eException.Message;
                }

                tmpTextBox.Text = header;
            }
        }
 public object GetProperty(string property)
 {
     NSOutlook.PropertyAccessor props = GetPropertyAccessor();
     try
     {
         object val = props.GetProperty(property);
         if (val is DBNull)
         {
             return(null);
         }
         return(val);
     }
     catch (System.Exception) { return(null); }
     finally
     {
         ComRelease.Release(props);
     }
 }
Beispiel #18
0
        public void dgvGetSMTPAddressForRecipients(DataGridView dgv)
        {
            const string PR_SMTP_ADDRESS =
                "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

            Outlook.Recipients recips = mail.Recipients;
            foreach (Outlook.Recipient recip in recips)
            {
                Outlook.PropertyAccessor pa = recip.PropertyAccessor;
                string smtpAddress          =
                    pa.GetProperty(PR_SMTP_ADDRESS).ToString();

                DataGridViewRow dgvr = new DataGridViewRow();
                dgvr.CreateCells(dgv);
                dgvr.Cells[0].Value = recip.Name;
                dgvr.Cells[1].Value = smtpAddress;
                dgv.Rows.Add(dgvr);

                //Debug.WriteLine(recip.Name + " SMTP=" + smtpAddress);
            }
        }
 private void ThisApplication_NewMail()
 {
     Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
                                .Session.GetDefaultFolder(Outlook
                                                          .OlDefaultFolders.olFolderInbox);
     Outlook.Items    inBoxItems = inBox.Items;
     Outlook.MailItem newEmail   = null;
     inBoxItems = inBoxItems.Restrict("[Unread] = true");
     try
     {
         foreach (object collectionItem in inBoxItems)
         {
             newEmail = collectionItem as Outlook.MailItem;
             Outlook.PropertyAccessor objPA = null;
             byte[] varX; //Dynamic
             if (newEmail != null)
             {
                 if (newEmail.Attachments.Count > 0)
                 {
                     for (int i = 1; i <= newEmail.Attachments.Count; i++)
                     {
                         newEmail.Attachments[i].SaveAsFile(@"C:\TestFileSave\" + newEmail.Attachments[i].FileName);
                         objPA = newEmail.Attachments[i].PropertyAccessor;
                         varX  = objPA.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37010102");
                         //newEmail.Attachments.Add(
                     }
                 }
             }
         }
     }
     catch (System.Exception ex)
     {
         string errorInfo = (string)ex.Message
                            .Substring(0, 11);
         if (errorInfo == "Cannot save")
         {
             MessageBox.Show(@"Create Folder C:\TestFileSave");
         }
     }
 }
        private String GetSMTPAddressForRecipients(Outlook.MailItem mail)
        {
            string smtpAddress = string.Empty;

            try
            {
                const string PR_SMTP_ADDRESS =
                    "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
                Outlook.Recipients recips = mail.Recipients;
                foreach (Outlook.Recipient recip in recips)
                {
                    Outlook.PropertyAccessor pa = recip.PropertyAccessor;
                    smtpAddress = smtpAddress + " " + pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                }
                smtpAddress = smtpAddress.Trim();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(smtpAddress);
        }
        //http://msdn.microsoft.com/en-us/library/office/ff184647.aspx
        private void GetSMTPAddressForRecipients(Outlook.MailItem mail)
        {
            const string PR_SMTP_ADDRESS =
                "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

            Outlook.Recipients recips = mail.Recipients;
            recips.ResolveAll();
            foreach (Outlook.Recipient recip in recips)
            {
                try {
                    Outlook.PropertyAccessor pa = recip.PropertyAccessor;
                    string smtpAddress          =
                        pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                    //if (!emails.Keys.Contains(smtpAddress)) emails.Add(smtpAddress, recip.Name );
                    SaveRecipient(smtpAddress, recip.Name);
                    SetSenderSubject(smtpAddress, mail.Subject);
                }
                catch (Exception ex)
                {
                }
            }
        }
Beispiel #22
0
        private Outlook.AddressList GetGlobalAddressList(Outlook.Application outlookApp, Outlook.Store store)
        {
            // Property string for the UID of a store or address list.
            string PR_EMSMDB_SECTION_UID =
                @"http://schemas.microsoft.com/mapi/proptag/0x3D150102";

            if (store == null)
            {
                throw new ArgumentNullException();
            }

            // Obtain the store UID using the proprety string and
            // property accessor on the store.
            Outlook.PropertyAccessor oPAStore = store.PropertyAccessor;

            // Convert the store UID to a string value.
            string storeUID = oPAStore.BinaryToString(oPAStore.GetProperty(PR_EMSMDB_SECTION_UID));

            // Enumerate each address list associated
            // with the session.
            foreach (Outlook.AddressList addrList in outlookApp.Session.AddressLists)
            {
                // Obtain the address list UID and convert it to
                // a string value.
                Outlook.PropertyAccessor oPAAddrList = addrList.PropertyAccessor;
                string addrListUID = oPAAddrList.BinaryToString(oPAAddrList.GetProperty(PR_EMSMDB_SECTION_UID));

                // Return the address list associated with the store
                // if the address list UID matches the store UID and
                // type is olExchangeGlobalAddressList.
                if (addrListUID == storeUID && addrList.AddressListType == Outlook.OlAddressListType.olExchangeGlobalAddressList)
                {
                    return(addrList);
                }
            }

            return(null);
        }
 private static Outlook.MAPIFolder GetCommonViewsFolder()
 {
     try
     {
         if (null == m_NameSpace)
         {
             Initialise();
         }
         Outlook.Store            olStore            = m_NameSpace.DefaultStore;
         Outlook.PropertyAccessor olPropertyAccessor = olStore.PropertyAccessor;
         string commonViewsEntryId = olPropertyAccessor.BinaryToString(olPropertyAccessor.GetProperty(PR_COMMON_VIEWS_ENTRY_ID));
         if (commonViewsEntryId != string.Empty)
         {
             return(m_NameSpace.GetFolderFromID(commonViewsEntryId));
         }
         return(null);
     }
     catch (Exception exception)
     {
         Console.WriteLine("Unable to get common views folder. Error: " + exception.ToString());
         return(null);
     }
 }
Beispiel #24
0
        public static string GetMailItemHeaderFrom(Outlook.MailItem mailItem)
        {
            if (mailItem == null)
            {
                return(string.Empty);
            }

            string
                TransportMessageHeadersSchema = "http://schemas.microsoft.com/mapi/proptag/0x007D001E",
                header = string.Empty;

            try
            {
                if (mailItem.PropertyAccessor != null)
                {
                    Outlook.PropertyAccessor
                        propertyAccessor = mailItem.PropertyAccessor;

                    header = (string)propertyAccessor.GetProperty(TransportMessageHeadersSchema);
                }

                Regex
                    r = new Regex("(?<=From:.*?<).*?(?=>)", RegexOptions.Singleline | RegexOptions.IgnoreCase);

                Match
                    match = r.Match(header);

                header = match.Success ? match.Value : string.Empty;
            }
            catch (Exception eException)
            {
                header = eException.Message;
            }

            return(header);
        }
Beispiel #25
0
        internal async Task ForwardItems()
        {
            Status = "Forwarding... pls wait!";
            Outlook.Folder         folder    = null;
            Cpty[]                 cpties    = new Cpty[0];
            IEnumerable <FileInfo> pdfFilles = null;

            if (SelectedArea == AuthFwd)
            {
                folder = GetOutlookFolder();
                if (folder == null)
                {
                    return;
                }
                if (folder.Items.Count == 0)
                {
                    Status = "No folder/items";
                    return;
                }
            }
            else
            {
                if (!GetPdfFiles(out pdfFilles))
                {
                    return;
                }
            }
            try
            {
                if (SelectedArea != AuthFwd)
                {
                    var savedCpties = await Cpty.Read(cpty_path);

                    cpties = PdfHelper.ToCpties(SelectedArea, pdfFilles, savedCpties).ToArray();
                    var dialog = new Counterparties();
                    dialog.DataContext = new PdfHelper()
                    {
                        Cpties = cpties
                    };
                    dialog.ShowDialog();
                    var allCpties = cpties.Concat(savedCpties.Where(s => s.BusinessArea != SelectedArea));
                    await Cpty.Save(allCpties, ConfigurationManager.AppSettings["cptiesPath"], txt => Status = txt);
                }
                await Task.Run(() =>
                {
                    if (SelectedArea == AuthFwd)
                    {
                        foreach (var obj in folder.Items)
                        {
                            if (obj is Outlook.MailItem mailItem)
                            {
                                #if DEBUG
                                Debug.WriteLine("forwarding mail: " + mailItem.Subject);
                                var recipientNames = new List <string>();
                                foreach (var objRecipient in mailItem.Recipients)
                                {
                                    if (objRecipient is Outlook.Recipient recipient)
                                    {
                                        Outlook.PropertyAccessor pa = recipient.PropertyAccessor;
                                        string smtpAddress          =
                                            pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                                        recipientNames.Add($"{recipient.Name} <{smtpAddress}>");
                                    }
                                }
                                Debug.WriteLine($"sent to {String.Join("; ", recipientNames)}");
                                #endif

                                var newItem = mailItem.Forward();
                                newItem.To  = AddressTo;
                                ComposeMail(newItem);
                            }
                        }
                    }
                    else
                    {
                        foreach (var cpty in cpties.Where(c => c.Active))
                        {
                            Outlook.MailItem mail = application.CreateItem(
                                Outlook.OlItemType.olMailItem) as Outlook.MailItem;
                            mail.Subject = SelectedArea + " - Netting Statement: " + cpty.Name;
                            mail.To      = cpty.EMail;
                            foreach (var pdf in cpty.pdfFilles)
                            {
                                mail.Attachments.Add(pdf.FullName,
                                                     Outlook.OlAttachmentType.olByValue, Type.Missing,
                                                     Type.Missing);
                            }
                            ComposeMail(mail);
                        }
                    }
                }
                               );

                Status = "Forward done.";
            }
            catch (Exception exc)
            {
                Status = exc.Message;
            }
        }
Beispiel #26
0
        internal static string GetSenderSMTPAddress(this Outlook.MailItem _mail)
        {
            if (_mail == null)
            {
                throw new ArgumentNullException();
            }

            if (_mail.SenderEmailType == "EX")
            {
                Outlook.AddressEntry sender = null;
                try
                {
                    sender = _mail.Sender;
                    if (sender != null)
                    {
                        //Now we have an AddressEntry representing the Sender
                        if (sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry ||
                            sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                        {
                            //Use the ExchangeUser object PrimarySMTPAddress
                            Outlook.ExchangeUser exchUser = null;
                            try
                            {
                                exchUser = sender.GetExchangeUser();
                                if (exchUser != null)
                                {
                                    return(exchUser.PrimarySmtpAddress);
                                }
                                else
                                {
                                    return(null);
                                }
                            }
                            finally
                            {
                                if (exchUser != null)
                                {
                                    Marshal.ReleaseComObject(exchUser);
                                    exchUser = null;
                                }
                            }
                        }
                        else
                        {
                            Outlook.PropertyAccessor propertyAccessor = null;
                            try
                            {
                                propertyAccessor = sender.PropertyAccessor;
                                if (propertyAccessor != null)
                                {
                                    try
                                    {
                                        return(propertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string);
                                    }
                                    catch (COMException) { }
                                }
                            }
                            finally
                            {
                                if (propertyAccessor != null)
                                {
                                    Marshal.ReleaseComObject(propertyAccessor);
                                    propertyAccessor = null;
                                }
                            }
                        }
                    }
                    else
                    {
                        return(null);
                    }
                }
                finally
                {
                    if (sender != null)
                    {
                        Marshal.ReleaseComObject(sender);
                        sender = null;
                    }
                }
            }
            else
            {
                return(_mail.SenderEmailAddress);
            }

            return(_mail.SenderEmailAddress);
        }
Beispiel #27
0
        public void OnActionMyButton_Click(Office.IRibbonControl control)
        {
            // Get selected calendar date
            Outlook.Application application = new Outlook.Application();
            Outlook.Explorer    explorer    = application.ActiveExplorer();
            Outlook.Folder      folder      = explorer.CurrentFolder as Outlook.Folder;
            Outlook.View        view        = explorer.CurrentView as Outlook.View;
            String recip_mail   = null;
            String title_mail   = null;
            String content_mail = null;

            if (view.ViewType == Outlook.OlViewType.olCalendarView)
            {
                //Outlook.CalendarView calView = view as Outlook.CalendarView;
                //DateTime calDateStart = calView.SelectedStartTime;
                //DateTime calDateEnd = calView.SelectedEndTime;

                // Do stuff with dates.
                //MessageBox.Show("relance test"+ calDateStart+"---"+ calDateEnd);

                const string PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
                try
                {
                    if (application.ActiveExplorer().Selection.Count > 0)
                    {
                        Object selObject = application.ActiveExplorer().Selection[1];


                        if (selObject is Outlook.AppointmentItem)
                        {
                            Outlook.AppointmentItem apptItem =
                                (selObject as Outlook.AppointmentItem);
                            title_mail   = apptItem.Subject;
                            content_mail = apptItem.Body;
                            Outlook.Recipients recips = apptItem.Recipients;
                            string             str    = null;

                            foreach (Outlook.Recipient recip in recips)
                            {
                                if (recip.MeetingResponseStatus != Outlook.OlResponseStatus.olResponseAccepted)
                                {
                                    Outlook.PropertyAccessor pa = recip.PropertyAccessor;
                                    string smtpAddress          =
                                        pa.GetProperty(PR_SMTP_ADDRESS).ToString();
                                    str += smtpAddress + ";";
                                }
                            }
                            if (str != null)
                            {
                                recip_mail = str;
                                //MessageBox.Show("Not responded: " + recip_mail);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                //MessageBox.Show("infomation: " + recip_mail+";"+ title_mail+";"+content_mail);
                if (recip_mail != null && title_mail != null && content_mail != null)
                {
                    sendMail(recip_mail, title_mail, content_mail);
                }
            }
        }
        public String GetRecipientEmail(Recipient recipient)
        {
            String retEmail = "";

            log.Fine("Determining email of recipient: " + recipient.Name);
            AddressEntry addressEntry;

            try {
                addressEntry = recipient.AddressEntry;
            } catch {
                log.Warn("Can't resolve this recipient!");
                addressEntry = null;
            }
            if (addressEntry == null)
            {
                log.Warn("No AddressEntry exists!");
                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                EmailAddress.IsValidEmail(retEmail);
                return(retEmail);
            }
            log.Fine("AddressEntry Type: " + recipient.AddressEntry.Type);
            if (recipient.AddressEntry.Type == "EX")   //Exchange
            {
                log.Fine("Address is from Exchange");
                if (recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry ||
                    recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                {
                    ExchangeUser eu = recipient.AddressEntry.GetExchangeUser();
                    if (eu != null && eu.PrimarySmtpAddress != null)
                    {
                        retEmail = eu.PrimarySmtpAddress;
                    }
                    else
                    {
                        log.Warn("Exchange does not have an email for recipient: " + recipient.Name);
                        try {
                            //Should I try PR_EMS_AB_PROXY_ADDRESSES next to cater for cached mode?
                            Microsoft.Office.Interop.Outlook.PropertyAccessor pa = recipient.PropertyAccessor;
                            retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                            log.Debug("Retrieved from PropertyAccessor instead.");
                        } catch {
                            log.Warn("Also failed to retrieve email from PropertyAccessor.");
                            retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                        }
                    }
                }
                else if (recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olOutlookContactAddressEntry)
                {
                    log.Fine("This is an Outlook contact");
                    ContactItem contact = null;
                    try {
                        contact = recipient.AddressEntry.GetContact();
                    } catch {
                        log.Warn("Doesn't seem to be a valid contact object. Maybe this account is not longer in Exchange.");
                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                    }
                    if (contact != null)
                    {
                        if (contact.Email1AddressType == "EX")
                        {
                            log.Fine("Address is from Exchange.");
                            log.Fine("Using PropertyAccessor to get email address.");
                            Microsoft.Office.Interop.Outlook.PropertyAccessor pa = contact.PropertyAccessor;
                            retEmail = pa.GetProperty(EMAIL1ADDRESS).ToString();
                        }
                        else
                        {
                            retEmail = contact.Email1Address;
                        }
                    }
                }
                else
                {
                    log.Fine("Exchange type: " + recipient.AddressEntry.AddressEntryUserType.ToString());
                    log.Fine("Using PropertyAccessor to get email address.");
                    Microsoft.Office.Interop.Outlook.PropertyAccessor pa = recipient.PropertyAccessor;
                    retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                }
            }
            else if (recipient.AddressEntry.Type.ToUpper() == "NOTES")
            {
                log.Fine("From Lotus Notes");
                //Migrated contacts from notes, have weird "email addresses" eg: "James T. Kirk/US-Corp03/enterprise/US"
                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
            }
            else
            {
                log.Fine("Not from Exchange");
                retEmail = recipient.AddressEntry.Address;
            }

            if (retEmail.IndexOf("<") > 0)
            {
                retEmail = retEmail.Substring(retEmail.IndexOf("<") + 1);
                retEmail = retEmail.TrimEnd(Convert.ToChar(">"));
            }
            log.Fine("Email address: " + retEmail, retEmail);
            EmailAddress.IsValidEmail(retEmail);
            return(retEmail);
        }
Beispiel #29
0
        // Récupération des informations du mail
        private void getSelectedItem(CommandBarButton Ctrl, ref bool CancelDefault)
        {
            try
            {
                // Récupération de l'item sélectionné
                Outlook.MailItem item = (Outlook.MailItem)outlook.ActiveExplorer().Selection[1];

                //Récupération du store ID
                Outlook.MAPIFolder store = (Outlook.MAPIFolder)item.Parent;

                // Création du PropertyAccessor
                Outlook.PropertyAccessor props = item.PropertyAccessor;

                // Déclenchement de l'event NewMail
                OnNewMail(new NewMailEventArgs(item.Subject, store.StoreID, item.EntryID, (String)props.GetProperty(this.messageIDParam)));

                Marshal.FinalReleaseComObject(props);
                Marshal.FinalReleaseComObject(store);
                Marshal.FinalReleaseComObject(item);
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                // On affiche l'erreur
                TrayIcon.afficheMessage("Exception sur récupération Outlook", e.Message + "\n" + e.ErrorCode.ToString());
            }
        }
        public String GetRecipientEmail(Recipient recipient)
        {
            String  retEmail       = "";
            Boolean builtFakeEmail = false;

            log.Fine("Determining email of recipient: " + recipient.Name);
            AddressEntry addressEntry     = null;
            String       addressEntryType = "";

            try {
                try {
                    addressEntry = recipient.AddressEntry;
                } catch {
                    log.Warn("Can't resolve this recipient!");
                    addressEntry = null;
                }
                if (addressEntry == null)
                {
                    log.Warn("No AddressEntry exists!");
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                }
                else
                {
                    try {
                        addressEntryType = addressEntry.Type;
                    } catch {
                        log.Warn("Cannot access addressEntry.Type!");
                    }
                    log.Fine("AddressEntry Type: " + addressEntryType);
                    if (addressEntryType == "EX")   //Exchange
                    {
                        log.Fine("Address is from Exchange");
                        if (addressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry ||
                            addressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                        {
                            ExchangeUser eu = null;
                            try {
                                eu = addressEntry.GetExchangeUser();
                                if (eu != null && eu.PrimarySmtpAddress != null)
                                {
                                    retEmail = eu.PrimarySmtpAddress;
                                }
                                else
                                {
                                    log.Warn("Exchange does not have an email for recipient: " + recipient.Name);
                                    Microsoft.Office.Interop.Outlook.PropertyAccessor pa = null;
                                    try {
                                        //Should I try PR_EMS_AB_PROXY_ADDRESSES next to cater for cached mode?
                                        pa       = recipient.PropertyAccessor;
                                        retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                                        log.Debug("Retrieved from PropertyAccessor instead.");
                                    } catch {
                                        log.Warn("Also failed to retrieve email from PropertyAccessor.");
                                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                                    } finally {
                                        pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa);
                                    }
                                }
                            } finally {
                                eu = (ExchangeUser)OutlookOgcs.Calendar.ReleaseObject(eu);
                            }
                        }
                        else if (addressEntry.AddressEntryUserType == OlAddressEntryUserType.olOutlookContactAddressEntry)
                        {
                            log.Fine("This is an Outlook contact");
                            ContactItem contact = null;
                            try {
                                try {
                                    contact = addressEntry.GetContact();
                                } catch {
                                    log.Warn("Doesn't seem to be a valid contact object. Maybe this account is no longer in Exchange.");
                                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                                }
                                if (contact != null)
                                {
                                    if (contact.Email1AddressType == "EX")
                                    {
                                        log.Fine("Address is from Exchange.");
                                        log.Fine("Using PropertyAccessor to get email address.");
                                        Microsoft.Office.Interop.Outlook.PropertyAccessor pa = null;
                                        try {
                                            pa       = contact.PropertyAccessor;
                                            retEmail = pa.GetProperty(EMAIL1ADDRESS).ToString();
                                        } finally {
                                            pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa);
                                        }
                                    }
                                    else
                                    {
                                        retEmail = contact.Email1Address;
                                    }
                                }
                            } finally {
                                contact = (ContactItem)OutlookOgcs.Calendar.ReleaseObject(contact);
                            }
                        }
                        else
                        {
                            log.Fine("Exchange type: " + addressEntry.AddressEntryUserType.ToString());
                            log.Fine("Using PropertyAccessor to get email address.");
                            Microsoft.Office.Interop.Outlook.PropertyAccessor pa = null;
                            try {
                                pa       = recipient.PropertyAccessor;
                                retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                            } finally {
                                pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa);
                            }
                        }
                    }
                    else if (addressEntryType != null && addressEntryType.ToUpper() == "NOTES")
                    {
                        log.Fine("From Lotus Notes");
                        //Migrated contacts from notes, have weird "email addresses" eg: "James T. Kirk/US-Corp03/enterprise/US"
                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                    }
                    else
                    {
                        log.Fine("Not from Exchange");
                        try {
                            if (string.IsNullOrEmpty(addressEntry.Address))
                            {
                                log.Warn("addressEntry.Address is empty.");
                                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                            }
                            else
                            {
                                retEmail = addressEntry.Address;
                            }
                        } catch (System.Exception ex) {
                            log.Fail("Failed accessing addressEntry.Address");
                            log.Fail(ex.Message);
                            retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                        }
                    }
                }

                if (retEmail != null && retEmail.IndexOf("<") > 0)
                {
                    retEmail = retEmail.Substring(retEmail.IndexOf("<") + 1);
                    retEmail = retEmail.TrimEnd(Convert.ToChar(">"));
                }
                log.Fine("Email address: " + retEmail, retEmail);
                if (!EmailAddress.IsValidEmail(retEmail) && !builtFakeEmail)
                {
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                    if (!EmailAddress.IsValidEmail(retEmail))
                    {
                        Forms.Main.Instance.Console.Update("Recipient \"" + recipient.Name + "\" with email address \"" + retEmail + "\" is invalid.<br/>" +
                                                           "This must be manually resolved in order to sync this appointment.", Console.Markup.error, notifyBubble: true);
                        throw new ApplicationException("Invalid recipient email for \"" + recipient.Name + "\"");
                    }
                }
                return(retEmail);
            } finally {
                addressEntry = (AddressEntry)OutlookOgcs.Calendar.ReleaseObject(addressEntry);
            }
        }