读取exchange邮件的未读数(转载)

protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("administrator的未读邮件数是:" + UnReadCount("administrator@domainname"));
        }
        int UnReadCount(string userMailAddress)
        {
            EwsConfig config = new EwsConfig();
            config.ExchangeVersion = ExchangeVersion.Exchange2010;
            //config.ExchangeVersion = ExchangeVersionType.Exchange2010_SP2;// ExchangeVersion.Exchange2010_SP3;
            config.EWSServiceUrl = "https://1.1.100.130/EWS/exchange.asmx";
            config.ExchangeAdministrator = "administrator";
            config.ExchangeAdministratorPassword = "password";
            config.DomainName = "domainname";
            config.OtherUserName = "";
            //下面这句屏蔽服务器证书验证,防止页面报“根据验证过程,远程证书无效”的错误
            ServicePointManager.ServerCertificateValidationCallback =
            delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
            ExchangeService service = new ExchangeService(config.ExchangeVersion);

            service.Credentials = new NetworkCredential(config.ExchangeAdministrator, config.ExchangeAdministratorPassword, config.DomainName);
            service.Url = new Uri(config.EWSServiceUrl);
            //前提打开Exchange 2010服务器在命令行中输入:
            //New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:
            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, config.OtherUserName);
            ImpersonatedUserId imperson = new ImpersonatedUserId();
            imperson.IdType = ConnectingIdType.SmtpAddress;
            imperson.Id = userMailAddress;
            service.ImpersonatedUserId = imperson;
            int unRead = Folder.Bind(service, WellKnownFolderName.Inbox).UnreadCount;
            return unRead;
            //HttpContext.Current.Response.Write(config.OtherUserName + "未读邮件数:" + unRead);
        }
        public struct EwsConfig
        {
            //ExchangeServiceBinding ser = new ExchangeServiceBinding();

            public ExchangeVersion ExchangeVersion;
            //public ExchangeVersionType ExchangeVersion;
            public string EWSServiceUrl;
            public string ExchangeAdministrator;
            public string ExchangeAdministratorPassword;
            public string DomainName;
            public string OtherUserName;

        }

 

以下是方法:

#region 给本人插入会议日程

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;


        public void CreateAppointment(ExchangeServiceBinding esb, string sub, string roommail, string location, DateTime datefrom, DateTime dateto,string bodyvalue)
        {
            // Create the appointment.
            CalendarItemType appointment = new CalendarItemType();
            // Add item properties to the appointment.
            appointment.Body = new BodyType();
            appointment.Body.BodyType1 = BodyTypeType.Text;
            appointment.Body.Value = bodyvalue;//"Agenda Items.";
            //appointment.Categories = new string[] { "Category1", "Category2" };
            appointment.Importance = ImportanceChoicesType.High;
            appointment.ImportanceSpecified = true;
            appointment.ItemClass = "IPM.Appointment";
            appointment.Subject = sub;
            // Add an attendee

            MailAddressCollection mc = GetrMailAddressList();
            AttendeeType[] rAtt = new AttendeeType[mc.Count];
            for (int ii = 0; ii < rAtt.Length; ii++)
            {
                EmailAddressType eat = new EmailAddressType();
                eat.EmailAddress = mc[ii].Address;
                eat.Name = mc[ii].DisplayName;
                AttendeeType att = new AttendeeType();
                att.Mailbox = eat;
                rAtt[ii] = att;
            }
            //EmailAddressType eat1 = new EmailAddressType();
            //eat1.EmailAddress = "第一个与会者邮箱地址";
            //eat1.Name = "姓名";
            //AttendeeType at1 = new AttendeeType();
            //at1.Mailbox = eat1;

            //EmailAddressType eat2 = new EmailAddressType();
            //eat2.EmailAddress = "第一二个与会者邮箱地址";
            //eat2.Name = "姓名";
            //AttendeeType at2 = new AttendeeType();
            //at2.Mailbox = eat2;
          
            //AttendeeType[] rAtt = new AttendeeType[2];
            //rAtt[0] = at1;
            //rAtt[1] = at2;
            appointment.RequiredAttendees = rAtt;

            //add meeting room attendee
            EmailAddressType meetingRoom = new EmailAddressType();
            meetingRoom.EmailAddress = roommail ;// "会议室邮箱地址";
            meetingRoom.Name =  location ;
            AttendeeType meetingType = new AttendeeType();
            meetingType.Mailbox = meetingRoom;
            AttendeeType[] meetingTypeList = new AttendeeType[1];
            meetingTypeList[0] = meetingType;
            appointment.Resources = meetingTypeList;
            appointment.Location = location;
            // Add calendar properties to the appointment.
            appointment.Start = datefrom;
            appointment.StartSpecified = true;
            appointment.End = dateto;
            appointment.EndSpecified = true;

            // Identify the destination folder that will contain the appointment.
            DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
            folder.Id = DistinguishedFolderIdNameType.calendar;

            // Create the array of items that will contain the appointment.
            NonEmptyArrayOfAllItemsType arrayOfItems = new NonEmptyArrayOfAllItemsType();
            arrayOfItems.Items = new ItemType[1];

            // Add the appointment to the array of items.
            arrayOfItems.Items[0] = appointment;

            // Create the CreateItem request.
            CreateItemType createItemRequest = new CreateItemType();
            // The SendMeetingInvitations attribute is required for calendar items.
            //createItemRequest.SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToNone;
            createItemRequest.SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToAllAndSaveCopy;
            createItemRequest.SendMeetingInvitationsSpecified = true;
            // Add the destination folder to the CreateItem request.
            createItemRequest.SavedItemFolderId = new TargetFolderIdType();
            createItemRequest.SavedItemFolderId.Item = folder;
            // Add the items to the CreateItem request.
            createItemRequest.Items = arrayOfItems;
            try
            {
                // Send the request and get the response.
                CreateItemResponseType createItemResponse = esb.CreateItem(createItemRequest);
                // Get the response messages.
                ResponseMessageType[] rmta = createItemResponse.ResponseMessages.Items;
                foreach (ResponseMessageType rmt in rmta)
                {
                    ArrayOfRealItemsType itemArray = ((ItemInfoResponseMessageType)rmt).Items;
                    ItemType[] items = itemArray.Items;

                    // Get the item identifier and change key for each item.
                    foreach (ItemType item in items)
                    {
                        Console.WriteLine("Item identifier: " + item.ItemId.Id);
                        Console.WriteLine("Item change key: " + item.ItemId.ChangeKey);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error Message: " + e.Message);
            }
        }
        //应答会议邀请:

        //应答会议邀请
        public static void AcceptItem(ExchangeServiceBinding esb, string meetingID)
        {
            // Create the request.
            CreateItemType request = new CreateItemType();

            // Set the message disposition on the request.
            request.MessageDisposition = MessageDispositionType.SendAndSaveCopy;
            request.MessageDispositionSpecified = true;

            // Create the AcceptItem response object.
            AcceptItemType acceptItem = new AcceptItemType();

            // Identify the meeting request to accept.
            acceptItem.ReferenceItemId = new ItemIdType();
            acceptItem.ReferenceItemId.Id = meetingID;

            // Add the AcceptItem response object to the request.
            request.Items = new NonEmptyArrayOfAllItemsType();
            request.Items.Items = new ItemType[1];
            request.Items.Items[0] = acceptItem;
            // Send the request and get the response.
            CreateItemResponseType response = esb.CreateItem(request);

            ArrayOfResponseMessagesType aormt = response.ResponseMessages;
            ResponseMessageType[] rmta = aormt.Items;
            foreach (ResponseMessageType rmt in rmta)
            {
                ItemInfoResponseMessageType iirmt = (rmt as ItemInfoResponseMessageType);
                if (iirmt.ResponseClass == ResponseClassType.Success)
                {
                    Console.WriteLine("Successfully accepted meeting");
                }
            }
        }

        private ExchangeServiceBinding esb;

        public static ExchangeServiceBinding GetExchangeService(ExchangeSession session)
        {
            ExchangeServiceBinding esb = new ExchangeServiceBinding();

            //esb.Credentials = session.GetNetworkCredential();
            string ocsuser = System.Configuration.ConfigurationManager.AppSettings["OcsUser"];
            string password = System.Configuration.ConfigurationManager.AppSettings["password"];
            string domain = System.Configuration.ConfigurationManager.AppSettings["Domain"];
            string ExchangeServer = System.Configuration.ConfigurationManager.AppSettings["ExchangeServer"];
            esb.Credentials = session.GetNetCS(ocsuser, password, domain );
            esb.Url = ExchangeServer; //session.Url;

            ServicePointManager.ServerCertificateValidationCallback += CheckCert;

            ExchangeImpersonationType imp = new ExchangeImpersonationType();
            imp.ConnectingSID = new ConnectingSIDType { PrimarySmtpAddress = session.Impersonation };
            esb.ExchangeImpersonation = imp;

            FindItemType fit = new FindItemType();
            fit.ItemShape = new ItemResponseShapeType { BaseShape = DefaultShapeNamesType.Default };
            fit.ParentFolderIds = new DistinguishedFolderIdType[]
            {
                new DistinguishedFolderIdType{ Id = DistinguishedFolderIdNameType.calendar }
            };

            fit.Traversal = ItemQueryTraversalType.Shallow;

            FindItemResponseType firt = esb.FindItem(fit);

            fit.Traversal = ItemQueryTraversalType.Shallow;

 

            return esb;
        }

        protected static bool CheckCert(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public void ExchangeOperation(string userMail)
        {
            //string unUserName = ConfigurationManager.AppSettings["UserName"];
            //string pnPassWord = ConfigurationManager.AppSettings["Password"];
            //string dnDomain = ConfigurationManager.AppSettings["Domain"];
            //string url = ConfigurationManager.AppSettings["Url"];

            //ExchangeImpersonationType Impersonation = new ExchangeImpersonationType();
            //Impersonation.ConnectingSID = new ConnectingSIDType();

            //esb = new ExchangeServiceBinding();
            //esb.Credentials = new System.Net.NetworkCredential(unUserName, pnPassWord, dnDomain);
            //esb.Url = url;
            //esb.ExchangeImpersonation = Impersonation;

            ExchangeSession m_Session = new ExchangeSession(userMail);
            try
            {
                esb = GetExchangeService(m_Session);
            }
            catch (Exception ex)
            {
                string strError = ex.Message;
            }
        }
        #endregion

这样使用

    //给本人差日程 20110419解决自己发的会议邀请,自己的日历看不到日程的问题
            ExchangeOperation(organigerEmail);//发起者的邮箱
            CreateAppointment(esb, meeting.Subject, organigerEmail , roomAddress, startTime, endTime, content.Text.Trim() );

webconfig配置:

  <!-- exchange配置-->
    <add key="ExchangeServer" value="https://10.0.8.13/EWS/Exchange.asmx"/>
    <add key="OcsUser" value="ocsuser"/>
    <add key="Domain" value="sinooceanland.com"/>
    <add key="password" value="password"/>

posted @ 2012-07-12 15:07  启明星工作室  阅读(1239)  评论(1编辑  收藏  举报