EWS Mail Operations (二)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Exchange.WebServices.Data;
using System.Net;
using System.IO;

namespace OfficeUtility
{
    /// <summary>
    /// A class used to query mail messages through Exchange Web Services (EWS) API.
    /// </summary>
    public class EWSMailSearchQuery
    {
        /// <summary>
        /// Gets and sets the mailbox address.
        /// </summary>
        public string Mailbox { get; set; }

        /// <summary>
        /// Gets and sets the mail address of the sender.
        /// </summary>
        public string SenderAddress { get; set; }

        /// <summary>
        /// Gets and sets the folder path under which mails are queried. i.e. "Inbox\ToMe".
        /// </summary>
        public string MailFolderPath { get; set; }

        /// <summary>
        /// Gets and sets the subject keywords, only mails whose subject contains all the words in this list will be kept.
        /// </summary>
        public List<string> SubjectKeywordList { get; set; }

        /// <summary>
        /// Gets and sets the subject excluded keywords, mails whose subject contains any word in this list will be excluded.
        /// </summary>
        public List<string> SubjectExcludedwordList { get; set; }

        /// <summary>
        /// Gets and sets the body keywords, only mails whose body contains all the words in this list will be kept.
        /// </summary>
        public List<string> BodyKeywordList { get; set; }

        /// <summary>
        /// Gets and sets the start date, only mails received after this day will be kept.
        /// </summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// Gets and sets the end date, only mails received before this day will be kept.
        /// </summary>
        public DateTime EndDate { get; set; }

        /// <summary>
        /// Create a new mail search query with existing Exchange service, email adress of sender,
        /// list of subject keywords, list of subject excluded words, list of mail body keywords,
        /// path of the mail folder, start date and end date.
        /// </summary>
        /// <param name="mailbox">Mailbox address.</param>
        /// <param name="senderAddress">Mail address of the sender.</param>
        /// <param name="mailFolderPath">The folder path under which mails are queried. i.e. "Inbox\ToMe".</param>
        /// <param name="subjectKeywordsList">Only mails whose subject contains all the words in this list will be kept.</param>
        /// <param name="subjectExcludedwordsList">Mails whose subject contains any word in this list will be excluded.</param>
        /// <param name="bodyKeywordsList">Only mails whose body contains all the words in this list will be kept.</param>
        /// <param name="startDate">Only mails received after this date will be kept.</param>
        /// <param name="endDate">Only mails received before this date will be kept.</param>
        public EWSMailSearchQuery(
            string mailbox,
            string senderAddress,
            string mailFolderPath,
            List<string> subjectKeywordsList, 
            List<string> subjectExcludedwordsList, 
            List<string> bodyKeywordsList,
            DateTime startDate, 
            DateTime endDate)
        {
            this.Mailbox = mailbox;
            this.SenderAddress = senderAddress;
            this.MailFolderPath = mailFolderPath;//.Split(new[] { '\\', }, StringSplitOptions.RemoveEmptyEntries);
            this.SubjectKeywordList = subjectKeywordsList;
            this.SubjectExcludedwordList = subjectExcludedwordsList;
            this.StartDate = startDate;
            this.EndDate = endDate;
            this.BodyKeywordList = bodyKeywordsList;
        }

        /// <summary>
        /// Create a new mail search query with existing Exchange service, email adress of sender,
        /// single subject keyword, single body keyword, path of the mail folder, start date and end date.
        /// </summary>
        /// <param name="senderAddress">The email address of the sender.</param>
        /// <param name="mailbox">Mailbox address.</param>
        /// <param name="mailFolderPath">The folder path under which mails are queried. i.e. "Inbox\ToMe".</param>
        /// <param name="subjectKeyword">Only mails whose subject contains the keyword will be kept</param>
        /// <param name="bodyKeyword">Only mails whose body contains the keyword will be kept</param>
        /// <param name="startDate">Only mails received after this date will be kept.</param>
        /// <param name="endDate">Only mails received before this date will be kept.</param>
        public EWSMailSearchQuery(
            string senderAddress, 
            string mailbox,
            string mailFolderPath,
            string subjectKeyword, 
            string bodyKeyword, 
            DateTime startDate, 
            DateTime endDate)
        {
            this.Mailbox = mailbox;
            this.SenderAddress = senderAddress;
            this.MailFolderPath = mailFolderPath;//.Split(new[] { '\\', }, StringSplitOptions.RemoveEmptyEntries);

            if (!string.IsNullOrEmpty(subjectKeyword))
            {
                this.SubjectKeywordList = new List<string>(new[] { subjectKeyword, });
            }

            if (!string.IsNullOrEmpty(bodyKeyword))
            {
                this.BodyKeywordList = new List<string>(new[] { bodyKeyword, });
            }

            this.StartDate = startDate;
            this.EndDate = endDate;
        }

        /// <summary>
        /// Search mails with specific search query.
        /// </summary>
        /// <param name="query">The EWSMailSearchQuery object.</param>
        /// <returns>A list of EmailMessage items.</returns>
        public static List<EmailMessage> SearchMail(ExchangeService service, EWSMailSearchQuery query)
        {
            List<SearchFilter> filters = new List<SearchFilter>();
            if (query.StartDate != DateTime.MinValue)
            {
                filters.Add(new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, query.StartDate));
            }

            if (query.EndDate != DateTime.MinValue)
            {
                filters.Add(new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, query.EndDate));
            }

            if (query.SubjectKeywordList != null)
            {
                foreach (string keyword in query.SubjectKeywordList)
                {
                    if (!string.IsNullOrEmpty(keyword))
                    {
                        filters.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword));
                    }
                }
            }

            if (query.SubjectExcludedwordList != null)
            {
                foreach (string keyword in query.SubjectExcludedwordList)
                {
                    if (!string.IsNullOrEmpty(keyword))
                    {
                        filters.Add(
                            new SearchFilter.Not(
                                new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword)));
                    }
                }
            }

            if (query.BodyKeywordList != null)
            {
                foreach (string keyword in query.BodyKeywordList)
                {
                    if (!string.IsNullOrEmpty(keyword))
                    {
                        filters.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword));
                    }
                }
            }

            return SearchMail(service, query.Mailbox, query.MailFolderPath, filters);
        }

        /// <summary>
        /// Search mails in a mailbox, under a specific folder and with specific search query.
        /// </summary>
        /// <param name="service">ExchangeService instance.</param>
        /// <param name="mailbox">Mailbox address.</param>
        /// <param name="mailFolderPath">The folder path under which mails are queried. i.e. "Inbox\ToMe".</param>
        /// <param name="filters">SearchFilter collection. Contains search conditions.</param>
        /// <returns>A list of EmailMessage items.</returns>
        public static List<EmailMessage> SearchMail(ExchangeService service, string mailbox, string mailFolderPath, List<SearchFilter> filters)
        {
            string[] folderPath = mailFolderPath.Split(new[] { '\\', }, StringSplitOptions.RemoveEmptyEntries);

            Mailbox box = new Mailbox(mailbox);
            FolderId folderId = null;

            if (folderPath == null || folderPath.Length <= 0)
            {
                folderId = new FolderId(WellKnownFolderName.Inbox, box);
            }
            else
            {
                switch (folderPath[0])
                {
                    case "Outbox":
                        folderId = new FolderId(WellKnownFolderName.Outbox, box);
                        break;
                    case "Drafts":
                        folderId = new FolderId(WellKnownFolderName.Drafts, box);
                        break;
                    case "Sent Items":
                        folderId = new FolderId(WellKnownFolderName.SentItems, box);
                        break;
                    case "Junk E-Mail":
                        folderId = new FolderId(WellKnownFolderName.JunkEmail, box);
                        break;
                    case "Deleted Items":
                        folderId = new FolderId(WellKnownFolderName.DeletedItems, box);
                        break;
                    case "Inbox":
                    default:
                        folderId = new FolderId(WellKnownFolderName.Inbox, box);
                        break;
                }

                for (int i = 1; i < folderPath.Length; i++)
                {
                    FindFoldersResults folders = service.FindFolders(folderId, new FolderView(int.MaxValue));
                    Folder folder = folders.FirstOrDefault(f => f.DisplayName == folderPath[i]);

                    if (folder != null)
                    {
                        folderId = folder.Id;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            FindItemsResults<Item> results = null;

            if (filters != null && filters.Count > 0)
            {
                results = service.FindItems(
                    folderId, 
                    new SearchFilter.SearchFilterCollection(LogicalOperator.And, filters),
                    new ItemView(int.MaxValue));
            }
            else
            {
                results = service.FindItems(folderId, new ItemView(int.MaxValue));
            }

            return results.OfType<EmailMessage>().ToList();
        }

        /// <summary>
        /// Download the required attachment files.
        /// </summary>
        /// <param name="service">ExchangeService instance.</param>
        /// <param name="item">The email message with the attachments.</param>
        /// <param name="attachmentKeywordsList">
        ///     Only files contain all the words in this list in their names will be downloaded.
        /// </param>
        /// <param name="excludedWordsList">Files with any word in this list in their names will be excluded.</param>
        /// <param name="localFolder">Folder saves the downloaded attachments.</param>
        /// <returns>A list of locations of saved files.</returns>
        public static List<string> DownloadAttachments(
            ExchangeService service, 
            EmailMessage item, 
            List<string> attachmentKeywordsList, 
            List<string> excludedWordsList, 
            string localFolder)
        {
            if (item == null)
            {
                return null;
            }

            List<string> attachmentList = new List<string>();

            EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments, ItemSchema.Subject));

            for (int i = 0; i < message.Attachments.Count; i++)
            {
                FileAttachment file = message.Attachments[i] as FileAttachment;
                if (file != null)
                {
                    string fileName = file.Name;
                    bool isRequired = true;

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

                    }

                    if (isRequired == true)
                    {
                        string filePath = Path.Combine(localFolder, file.Name);
                        if (!Directory.Exists(localFolder))
                        {
                            Directory.CreateDirectory(localFolder);
                        }

                        file.Load(filePath);
                        attachmentList.Add(filePath);
                    }
                }
            }

            return attachmentList;
        }

        /// <summary>
        /// Download the required attachment files.
        /// </summary>
        /// <param name="service">ExchangeService instance.</param>
        /// <param name="item">The email message with the attachments.</param>
        /// <param name="keyword">Only files contain this word in their name will be downloaded.</param>
        /// <param name="excludedWord">Files with this word in their names will be excluded.</param>
        /// <param name="localFolder">Folder saves the downloaded attachments.</param>
        /// <returns>A list of locations of saved files.</returns>
        public static List<string> DownloadAttachments(
            ExchangeService service,
            EmailMessage item,
            string keyword, 
            string excludedWord, 
            string localFolder)
        {
            if (item == null)
            {
                return null;
            }

            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(service, item, keywordList, excludedWordList, localFolder);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值