• 使用.NET读取exchange邮件


    公司有个第3方的系统,不能操作源码修改错误捕获,但是错误会发一个邮件出来,里面包含了主要的信息。于是想从邮件下手,提取需要的数据

    开始考虑使用的是exchange service,主要参考http://blog.csdn.net/tider_ys/article/details/6637879

    中间遇到几个问题,稍微记录一下:

    1. The request failed with HTTP status 401: Unauthorized XXXX。添加web service的时候,使用的地址应该是 https://<server name>/EWS/Services.wsdl 这种形式,但是在给ExchangeServiceBinding.Url赋值,然后连接exchange servervice的时候,报错。通过程序call service,使用的地址 https://<server name>/EWS/Exchange.asmx

    http://www.windows-server-answers.com/microsoft/Exchange-Development/30599015/the-request-failed-with-http-status-405-method-not-allowed.aspx

    2. The remote certificate is invalid according to the validation procedure。建立连接时报错,稍微添加一点点代码

    ServicePointManager.ServerCertificateValidationCallback = (obj, certificate, chain, errors) => true;

    https://social.msdn.microsoft.com/Forums/en-US/98aa34b2-69b5-4b8a-8f77-2a3f08869e3b/the-remote-certificate-is-invalid-according-to-the-validation-procedure?forum=exchangesvrdevelopment

    关于exchange webservice,可以参考http://msdn.microsoft.com/en-us/library/office/exchangewebservices(v=exchg.150).aspx

    做到后来发现,如果直接使用exchange service,需要一步步查找邮件文件夹,搜索邮件,获取邮件内容,代码写起来也有点乱,不是很容易懂。参考资料也比较少,比如我要查收件箱下的一个文件夹test,需要FolderId,但这个值怎么取还挺麻烦,看到的代码大部分都是遍历子文件夹,然后比较名字。刚好在这个过程中,发现微软已经提供了新的API来操作exchange,EWS Managed API

    Working with the EWS Managed API 2.0

    看了一些sample之后,这个API要比直接访问web service方便得多,操作方式简单易懂,代码也更简洁,可读性更好。而且,还是开源的https://github.com/OfficeDev/ews-managed-api

    要连接exchange server,不再需要指定url,而是可以通过ExchangeService.AutodiscoverUrl

    public ExchangeService GetService()
    {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
    
        service.Credentials = new NetworkCredential("test@test.com", "test");
    
        service.AutodiscoverUrl("test@test.com", RedirectionUrlValidationCallback);
    
        return service;
    }

    用代码来说话,查找收件箱中的子文件夹"Test Service",查找文件夹中标题为"Test email"且发送时间在2014/11/28之后的邮件

    private void CheckEmail()
    {
        ExchangeService service = GetService();
    
        //find sub folder in inbox
        FolderId folder = FindFolderIdByDisplayName(service, "Test Service", WellKnownFolderName.Inbox);
    
        //prepare search filter
        List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
    
        //subject filter
        searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Test email"));
    
        //date time received filter
        DateTime lastProcessedTime = new DateTime(2014, 11, 28, 0, 0, 0);
        searchFilterCollection.Add(new SearchFilter.IsGreaterThan(ItemSchema.DateTimeSent, lastProcessedTime));
    
        //operator: and
        SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray());
    
        int offset = 0;
        int pageSize = 20;
        bool MoreItems = true;
    
        //search in pages
        while (MoreItems)
        {
            ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
            FindItemsResults<Item> findResults = service.FindItems(folder, searchFilter, view);
            foreach (Item myItem in findResults.Items)
            {
                //body message does not include in returned properties, get message details
                Item item = Item.Bind(service, myItem.Id);
                //Process(item);
            }
    
            //last page
            if (!findResults.MoreAvailable)
                MoreItems = false;
    
            //next page
            if (MoreItems)
                offset += pageSize;
        }
    }

    可以看到整个代码比直接访问web service简洁不少,更容易理解

    微软官方实例代码下载:https://code.msdn.microsoft.com/Exchange-2013-101-Code-3c38582c

  • 相关阅读:
    shell脚本编程-结构化命令3-while、until命令
    shell脚本编程-结构化命令2-for命令
    sscanf解析复杂字符串,双引号通配符的使用问题
    shell脚本编程-结构化命令1-分支语句
    shell脚本编程基础
    linux系统管理的基本命令2
    linux系统管理的基本命令
    redis
    Eclipse启动报错
    java斗地主发牌源码
  • 原文地址:https://www.cnblogs.com/kofkyo/p/EWS_Managed_API.html
Copyright © 2020-2023  润新知