Office Outlook API (三) Search Emails

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Outlook;
using System.IO;

namespace OfficeUtility
{
    /// <summary>
    /// About how to search a mail
    /// </summary>
    public class OutlookMailSearchQuery
    {
        public string AccountName { get; set; }
        public string Sender { get; set; }
        public List<string> ReceiverList { get; set; }
        public string MailFolderPath { get; set; }
        public List<string> SubjectKeywordList { get; set; }
        public List<string> SubjectExcludedwordList { get; set; }
        public List<string> BodyKeywordList { get; set; }
        public List<string> AttachFileList { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }

        /// <summary>
        /// Create a new mail search query with accountName, sender, subjectKeywordList, subjectExcludedwordList, bodyKeywordList, mailFolderPath, startDate, endDate
        /// </summary>
        /// <param name="accountName">Like "Meizhi Hu", "Asia ETI automation"</param>
        /// <param name="sender">The ailas who sent the mail</param>
        /// <param name="subjectKeywordList">Only the mail whose subject contains all the words in this list will be kept</param>
        /// <param name="subjectExcludedwordList">Mail whose subject contains any word in this list will be excluded</param>
        /// <param name="bodyKeywordList">Only the mail whose body contains all the keyword in this list will be kept</param>
        /// <param name="mailFolderPath">The folder path under which the mail is </param>
        /// <param name="startDate">Only the mail whose received date is after this "startDate" will be kept </param>
        /// <param name="endDate">Only the mail whose received date is before this "endDate" will be kept</param>
        public OutlookMailSearchQuery(string accountName, string sender, List<string> subjectKeywordList, List<string> subjectExcludedwordList, List<string> bodyKeywordList,string mailFolderPath, DateTime startDate, DateTime endDate)
        {
            this.AccountName = accountName;
            this.Sender = sender;
            this.MailFolderPath = mailFolderPath;
            this.StartDate = startDate;
            this.EndDate = endDate;
            this.SubjectKeywordList = subjectKeywordList;
            this.SubjectExcludedwordList = subjectExcludedwordList;
            this.BodyKeywordList = bodyKeywordList;
            this.ReceiverList = new List<string>();
            this.AttachFileList = new List<string>();
        }

        /// <summary>
        /// Create a new mail search query with accountName, sender, subjectKeyword, bodyKeyword, mailFolderPath, startDate, endDate
        /// </summary>
        /// <param name="accountName">Like "Meizhi Hu", "Asia ETI automation"</param>
        /// <param name="sender">The ailas who sent the mail</param>
        /// <param name="subjectKeywordList">Only the mail whose subject contains the keyword will be kept</param>
        /// <param name="bodyKeywordList">Only the mail whose body contains the keyword will be kept</param>
        /// <param name="mailFolderPath">The folder path under which the mail is </param>
        /// <param name="startDate">Only the mail whose received date is after this "startDate" will be kept </param>
        /// <param name="endDate">Only the mail whose received date is before this "endDate" will be kept</param>
        public OutlookMailSearchQuery(string accountName, string sender, string subjectKeyword,string bodyKeyword, string mailFolderPath, DateTime startDate, DateTime endDate)
        {
            if (!string.IsNullOrEmpty(subjectKeyword))
            {
                List<string> subjectKeywordList = new List<string>();
                subjectKeywordList.Add(subjectKeyword);
                this.SubjectKeywordList = subjectKeywordList;
            }

            if (!string.IsNullOrEmpty(bodyKeyword))
            {
                List<string> bodyKeywordList = new List<string>();
                bodyKeywordList.Add(bodyKeyword);
                this.BodyKeywordList = bodyKeywordList;
            }

            this.AccountName = accountName;
            this.Sender = sender;
            this.MailFolderPath = mailFolderPath;
            this.StartDate = startDate;
            this.EndDate = endDate;
            this.ReceiverList = new List<string>();
            this.AttachFileList = new List<string>();
        }

        /// <summary>
        /// Search mail with the outlook mail search query
        /// </summary>
        /// <param name="outlookApp"></param>
        /// <param name="query"></param>
        /// <returns>MailItem list</returns>
        public static List<MailItem> SearchMail(OutlookApp outlookApp, OutlookMailSearchQuery query)
        {
            List<MailItem> mailList = new List<MailItem>();
            MAPIFolder folder = SearchTargetMailAccount(outlookApp, query.AccountName);
            folder = GetFolderPath(folder, query.MailFolderPath);
            mailList = GetMailsSendInCertainTime(folder, query.StartDate, query.EndDate);
            mailList = GetMailsFromCertainAddress(mailList, query.Sender);
            mailList = GetMailsWithCertainSubject(mailList, query.SubjectKeywordList);
            mailList = GetMailsWithoutCertainSubject(mailList, query.SubjectExcludedwordList);
            return mailList;
        }

        /// <summary>
        /// Search mails in specified sub folders under a specified account
        /// </summary>
        /// <param name="outlookApp"></param>
        /// <param name="accountName">Meizhi Hu as an example</param>
        /// <param name="subFolderPath">Inbox\Private as an example</param>
        /// <returns>MailItem list</returns>
        public static List<MailItem> SearchEmailInSpecifiedFolder(OutlookApp outlookApp, string accountName, string subFolderPath)
        {
            MAPIFolder mapiFolder = SearchTargetMailAccount(outlookApp, accountName);
            List<MailItem> mailList = SearchEmailInSpecifiedFolder(mapiFolder, subFolderPath);
            return mailList;
        }

        /// <summary>
        /// Search the MAPIFolder in a specified account
        /// </summary>
        /// <param name="outlookApp"></param>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public static MAPIFolder SearchTargetMailAccount(OutlookApp outlookApp, string accountName)
        {
            _NameSpace ns = outlookApp.OutlookAppInstance.GetNamespace("MAPI");
            ns.Logon(null, null, false, false);
            MAPIFolder folder = null;
            try
            {
                Folders folders = outlookApp.OutlookAppInstance.Application.Session.Folders;

                foreach (MAPIFolder item in folders)
                {
                    if (item.Name.Contains(accountName))
                    {
                        folder = item;
                        break;
                    }
                }
            }

            catch (System.Exception ex)
            {
                throw new System.Exception(string.Format("Error found when searching the target mail account {0}. The exception message is: {1}", accountName, ex.Message));
            }
            return folder;
        }

        /// <summary>
        /// Search mails in specified sub folders
        /// </summary>
        /// <param name="mapiFolder"></param>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public static List<MailItem> SearchEmailInSpecifiedFolder(MAPIFolder mapiFolder, string folderPath)
        {
            List<MailItem> itemList = new List<MailItem>();

            try
            {
                mapiFolder = GetFolderPath(mapiFolder, folderPath);
                Items items = mapiFolder.Items;

                for (int i = 1; i <= items.Count; i++)
                {
                    MailItem item = (MailItem)items[i];
                    itemList.Add(item);
                }
            }

            catch (System.Exception ex)
            {
                throw new System.Exception(string.Format("Error happens when searching mails in the mailFolder {0} under {1}. Exception message: {2}", mapiFolder.Name, folderPath, ex.Message));
            }
            return itemList;
        }

        public static MAPIFolder GetFolderPath(MAPIFolder mapiFolder, string folderPath)
        {
            string[] folderPathArr = folderPath.Split('\\');
            for (int i = 0; i < folderPathArr.Length; i++)
            {
                mapiFolder = mapiFolder.Folders[folderPathArr[i]];
            }

            return mapiFolder;
        }

        /// <summary>
        /// Search and get emails by email address
        /// </summary>
        /// <param name="itemList"></param>
        /// <param name="senderEmailAddress"></param>
        /// <returns></returns>
        public static List<MailItem> GetMailsFromCertainAddress(List<MailItem> itemList, string senderEmailAddress)
        {
            List<MailItem> mailList = new List<MailItem>();
            foreach (MailItem item in itemList)
            {
                if (item.SenderEmailAddress.ToLower().Contains(senderEmailAddress.ToLower()))
                {
                    mailList.Add(item);
                }
            }
            return mailList;
        }

        /// <summary>
        /// Search emails which subject contains the subject keyword
        /// </summary>
        /// <param name="itemList"></param>
        /// <param name="subjectKeyword"></param>
        /// <returns></returns>
        public static List<MailItem> GetMailsWithCertainSubject(List<MailItem> itemList, string subjectKeyword)
        {
            if (string.IsNullOrEmpty(subjectKeyword))
            {
                return itemList;
            }
            else
            {
                List<MailItem> mailList = new List<MailItem>();
                foreach (MailItem item in itemList)
                {
                    if (item.Subject.Contains(subjectKeyword))
                    {
                        mailList.Add(item);
                    }
                }
                return mailList;
            }
        }

        /// <summary>
        ///  Search emails which subject contains the subject keyword
        /// </summary>
        /// <param name="itemList"></param>
        /// <param name="subjectKeywordList"></param>
        /// <returns></returns>
        public static List<MailItem> GetMailsWithCertainSubject(List<MailItem> itemList, List<string> subjectKeywordList)
        {
            List<MailItem> mailList = new List<MailItem>();
            if (subjectKeywordList == null || subjectKeywordList.Count == 0)
            {
                mailList = itemList;
            }

            else
            {
                foreach (MailItem item in itemList)
                {
                    string subject = item.Subject;
                    bool isRequired = true;

                    foreach (string keyword in subjectKeywordList)
                    {
                        if (isRequired == true)
                        {
                            isRequired = subject.Contains(keyword);
                        }
                        else
                            break;
                    }

                    if (isRequired == true)
                    {
                        mailList.Add(item);
                    }
                }
            }
            return mailList;
        }

        /// <summary>
        ///  Search emails which subject doesn't contains the subject keyword
        /// </summary>
        /// <param name="itemList"></param>
        /// <param name="excludedKeywordList"></param>
        /// <returns></returns>
        public static List<MailItem> GetMailsWithoutCertainSubject(List<MailItem> itemList, List<string> excludedKeywordList)
        {
            List<MailItem> mailList = new List<MailItem>();
            if (excludedKeywordList == null || excludedKeywordList.Count == 0)
            {
                mailList = itemList;
            }

            else
            {
                foreach (MailItem item in itemList)
                {
                    string subject = item.Subject;
                    bool isRequired = true;
                    foreach (string keyword in excludedKeywordList)
                    {
                        if (isRequired == true)
                        {
                            isRequired = !subject.Contains(keyword);
                        }
                        else
                            break;
                    }

                    if (isRequired == true)
                    {
                        mailList.Add(item);
                    }
                }
            }
            return mailList;
        }

        /// <summary>
        /// Search the mail which was sent between start time and end time
        /// </summary>
        /// <param name="itemList"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public static List<MailItem> GetMailsSendInCertainTime(List<MailItem> itemList, DateTime startTime, DateTime endTime)
        {
            List<MailItem> mailList = new List<MailItem>();
            foreach (MailItem item in itemList)
            {
                if (item.ReceivedTime.Date >= startTime.Date && item.ReceivedTime.Date <= endTime.Date)
                {
                    mailList.Add(item);
                }
            }
            return mailList;
        }

        public static List<MailItem> GetMailsSendInCertainTime(MAPIFolder folder, DateTime startTime, DateTime endTime)
        {
            List<MailItem> mailList = new List<MailItem>();
            try
            {
                Items items = folder.Items;

                for (int i = 1; i <= items.Count; i++)
                {
                    try
                    {
                        MailItem item = (MailItem)items[i];
                        if (item.ReceivedTime >= startTime && item.ReceivedTime <= endTime)
                        {
                            mailList.Add(item);
                        }
                    }
                    catch (System.Exception ex)
                    {

                    }
                }
            }

            catch (System.Exception ex)
            {
                throw new System.Exception(string.Format("Error found when searching mails between {0} and {1}", startTime.ToString("yyyyMMdd"), endTime.ToString("yyyyMMdd")));
            }
            return mailList;


        }

        /// <summary>
        /// Download the required attachment file
        /// </summary>
        /// <param name="item"></param>
        /// <param name="attachmentKeywordList"></param>
        /// <param name="excludedWordList"></param>
        /// <param name="savedDir"></param>
        /// <returns></returns>
        public static List<string> DownloadAttachments(MailItem item, List<string> attachmentKeywordList, List<string> excludedWordList, string savedDir)
        {
            List<string> attachmentList = new List<string>();
            if (item == null)
            {
                return null;
            }
            foreach (Attachment attachment in item.Attachments)
            {
                bool isRequired = true;
                string fileName = attachment.FileName;
                if (attachmentKeywordList != null && attachmentKeywordList.Count != 0)
                {
                    foreach (string keyword in attachmentKeywordList)
                    {
                        if (isRequired == true)
                        {
                            if (!fileName.Contains(keyword))
                            {
                                isRequired = false;
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                //if (isRequired == false)
                //{
                //    break;
                //}

                else
                {
                    if (excludedWordList != null && excludedWordList.Count != 0)
                    {
                        foreach (string excludedWord in excludedWordList)
                        {
                            if (isRequired == true)
                            {
                                if (fileName.Contains(excludedWord))
                                {
                                    isRequired = false;
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }

                if (isRequired == true)
                {
                    string filePath = Path.Combine(savedDir, attachment.FileName);
                    if (!Directory.Exists(savedDir))
                    {
                        Directory.CreateDirectory(savedDir);
                    }
                    attachment.SaveAsFile(filePath);
                    attachmentList.Add(filePath);
                }
            }

            return attachmentList;
        }

        /// <summary>
        /// Download the required attachment file
        /// </summary>
        /// <param name="item"></param>
        /// <param name="keyword"></param>
        /// <param name="excludedWord"></param>
        /// <param name="savedDir"></param>
        /// <returns></returns>
        public static List<string> DownloadAttachments(MailItem item, string keyword, string excludedWord, string savedDir)
        {
            List<string> attachmentList = new List<string>();
            List<string> keywordList = new List<string>();
            if (!string.IsNullOrEmpty(keyword))
            {
                keywordList.Add(keyword);
            }
            List<string> excludedWordList = new List<string>();
            if (!string.IsNullOrEmpty(excludedWord))
            {
                excludedWordList.Add(excludedWord);
            }
            return DownloadAttachments(item, keywordList, excludedWordList, savedDir);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值