想想自己的目标,看看自己的行动。

鱼缸里的鲸鱼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

      通过Exchange Server 2007整合与二次开发---入门篇,相信对Exchange Server 2007二次开发有了初步的了解,在本文中,是我在项目中对EWS的具体应用。

      要使用EWS,首先要设置ExchangeServiceBinding代理类,如下:

            ExchangeServiceBinding esb = new ExchangeServiceBinding();

            esb.Url = EWS地址;
            esb.Credentials = new NetworkCredential(用户名, 密码, 域名);

            这样我们就创建了该用户的代理,通过这个代理可以进行收发邮件、预定会议、应答会议等。

            也可以用这种方式创建esb.Credentials=CredentialCache.DefaultCredentials,这样为当前登录系统的账户创建代理。

以下是一些具体的应用示例:

 创建普通邮件:

 1public static void CreateEmail(ExchangeServiceBinding esb)
 2        {
 3            createItemRequest = new CreateItemType();
 4            createItemRequest.MessageDisposition = MessageDispositionType.SendAndSaveCopy;
 5            createItemRequest.MessageDispositionSpecified = true;
 6            // Specify the location of sent items. 
 7            createItemRequest.SavedItemFolderId = new TargetFolderIdType();
 8            DistinguishedFolderIdType sentitems = new DistinguishedFolderIdType();
 9            sentitems.Id = DistinguishedFolderIdNameType.sentitems;
10            createItemRequest.SavedItemFolderId.Item = sentitems;
11            // Create the array of items.
12            createItemRequest.Items = new NonEmptyArrayOfAllItemsType();
13            // Create a single e-mail message.
14            MessageType message = new MessageType();
15            message.Subject = "test";
16            message.Body = new BodyType();
17            message.Body.BodyType1 = BodyTypeType.Text;     
18            message.Body.Value = "this is a test mail from exchange services";
19            message.ItemClass = "IPM.Note";
20            message.From = new SingleRecipientType();
21            message.From.Item = new EmailAddressType();
22            message.ToRecipients = new EmailAddressType[1];
23            message.ToRecipients[0= new EmailAddressType();            
24message.ToRecipients[0].EmailAddress = "收件人地址";
25            message.Sensitivity = SensitivityChoicesType.Confidential;
26            message.Importance = ImportanceChoicesType.High;
27            // Add the message to the array of items to be created.
28            createItemRequest.Items.Items = new ItemType[1];
29            createItemRequest.Items.Items[0= message;
30            try
31            {
32                // Send the request to create and send the e-mail item, and get the response.
33                CreateItemResponseType createItemResponse = esb.CreateItem(createItemRequest);
34                // Determine whether the request was a success.
35                if (createItemResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
36                {
37                    throw new Exception(createItemResponse.ResponseMessages.Items[0].MessageText);
38                }

39                else
40                {
41                    Console.WriteLine("Item was created");
42                }

43
44            }

45            catch (Exception e)
46            {
47                Console.WriteLine(e.Message);
48            }

49
50        }

若要代某人发送邮件,只需添加以下代码,但要注意,EWS代理账户需要对实际发送者有代理发送邮件权限,否则会收到发送失败的邮件。

message.From = new SingleRecipientType();
message.From.Item = new EmailAddressType();
message.From.Item.EmailAddress = "实际的发送者邮件地址";

创建带附件的邮件:

  1创建带附件的邮件
  2public static ItemIdType CreateMessage(ExchangeServiceBinding esb, string subject,string body,string toEmailAddress)
  3        {
  4            ItemIdType iiItemid = new ItemIdType();
  5            // Create a CreateItem request object
  6            CreateItemType request = new CreateItemType();
  7           
  8            // Setup the request:
  9            // Indicate that we only want to send the message. No copy will be saved.
 10            request.MessageDisposition = MessageDispositionType.SaveOnly;
 11            request.MessageDispositionSpecified = true;
 12
 13            // Create a message object and set its properties
 14            MessageType message = new MessageType();
 15            message.Subject = subject;
 16            message.Body = new BodyType();
 17            message.Body.BodyType1 = BodyTypeType.Text;
 18            message.Body.Value = body;
 19
 20            message.ToRecipients = new EmailAddressType[1];
 21            message.ToRecipients[0= new EmailAddressType();
 22            message.ToRecipients[0].EmailAddress = toEmailAddress;
 23            message.ToRecipients[0].RoutingType = "SMTP";
 24
 25            //Note: Same you can set CC and BCC Recipients
 26
 27            // Construct the array of items to send
 28            request.Items = new NonEmptyArrayOfAllItemsType();
 29            request.Items.Items = new ItemType[1];
 30            request.Items.Items[0= message;
 31
 32            // Call the CreateItem EWS method.
 33            CreateItemResponseType createItemResponse = esb.CreateItem(request);
 34   
 35            if (createItemResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
 36            {
 37                Console.WriteLine("Error Occured");
 38                Console.WriteLine(createItemResponse.ResponseMessages.Items[0].MessageText);
 39            }

 40            else
 41            {
 42                ItemInfoResponseMessageType rmResponseMessage = createItemResponse.ResponseMessages.Items[0as ItemInfoResponseMessageType;
 43
 44                Console.WriteLine("Item was created");
 45
 46                Console.WriteLine("Item ID : " + rmResponseMessage.Items.Items[0].ItemId.Id.ToString());
 47
 48                Console.WriteLine("ChangeKey : " + rmResponseMessage.Items.Items[0].ItemId.ChangeKey.ToString());
 49
 50
 51                iiItemid.Id = rmResponseMessage.Items.Items[0].ItemId.Id.ToString();
 52
 53                iiItemid.ChangeKey = rmResponseMessage.Items.Items[0].ItemId.ChangeKey.ToString();
 54            }

 55            return iiItemid;
 56        }

 57
 58//Here the itemID is returned by the CreateMessage Function         
 59        private static ItemIdType CreateAttachment(ExchangeServiceBinding ewsServiceBinding, String fnFileName, ItemIdType iiCreateItemid)
 60        {
 61
 62            ItemIdType iiAttachmentItemid = new ItemIdType();
 63
 64            FileStream fsFileStream = new FileStream(fnFileName, System.IO.FileMode.Open,
 65
 66            System.IO.FileAccess.Read);
 67
 68            byte[] bdBinaryData = new byte[fsFileStream.Length];
 69
 70            long brBytesRead = fsFileStream.Read(bdBinaryData, 0, (int)fsFileStream.Length);
 71
 72            fsFileStream.Close();
 73
 74            FileAttachmentType faFileAttach = new FileAttachmentType();
 75
 76            faFileAttach.Content = bdBinaryData;
 77
 78            faFileAttach.Name = fnFileName;
 79
 80            CreateAttachmentType amAttachmentMessage = new CreateAttachmentType();
 81
 82            amAttachmentMessage.Attachments = new AttachmentType[1];
 83
 84            amAttachmentMessage.Attachments[0= faFileAttach;
 85
 86            amAttachmentMessage.ParentItemId = iiCreateItemid;
 87
 88            CreateAttachmentResponseType caCreateAttachmentResponse = ewsServiceBinding.CreateAttachment
 89
 90            (amAttachmentMessage);
 91
 92            if (caCreateAttachmentResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
 93            {
 94
 95                Console.WriteLine("Error Occured");
 96
 97                Console.WriteLine(caCreateAttachmentResponse.ResponseMessages.Items[0].MessageText);
 98
 99            }

100
101            else
102            {
103
104                AttachmentInfoResponseMessageType amAttachmentResponseMessage =
105
106                caCreateAttachmentResponse.ResponseMessages.Items[0as AttachmentInfoResponseMessageType;
107
108                Console.WriteLine("Attachment was created");
109
110                Console.WriteLine("Change Key : " + amAttachmentResponseMessage.Attachments
111
112                [0].AttachmentId.RootItemChangeKey.ToString());
113
114                iiAttachmentItemid.Id = amAttachmentResponseMessage.Attachments[0].AttachmentId.RootItemId.ToString
115
116                ();
117
118                iiAttachmentItemid.ChangeKey = amAttachmentResponseMessage.Attachments
119
120                [0].AttachmentId.RootItemChangeKey.ToString();
121
122            }

123
124            return iiAttachmentItemid;
125
126        }

127
128  public static bool SendMessage(ExchangeServiceBinding esb, ItemIdType p_itemId)
129        {
130            bool blnResult = false;
131            SendItemType siSendItem = new SendItemType();
132            siSendItem.ItemIds = new BaseItemIdType[1];
133            siSendItem.SavedItemFolderId = new TargetFolderIdType();
134            DistinguishedFolderIdType siSentItemsFolder = new DistinguishedFolderIdType();
135            siSentItemsFolder.Id = DistinguishedFolderIdNameType.sentitems;
136            siSendItem.SavedItemFolderId.Item = siSentItemsFolder;
137            siSendItem.SaveItemToFolder = true;
138
139            siSendItem.ItemIds[0= (BaseItemIdType)p_itemId;
140            SendItemResponseType srSendItemResponseMessage = esb.SendItem(siSendItem);
141            if (srSendItemResponseMessage.ResponseMessages.Items[0].ResponseClass ==
142               ResponseClassType.Success)
143            {
144                blnResult = true;
145            }

146            else
147            {
148                blnResult = false;
149            }

150            return blnResult;
151        }

152

调用过程如下所示:
            ItemIdType iiCreateItemid = CreateMessage(esb,"test mail with attachment","this is a mail for testing attachment","收件人邮箱地址");

            iiCreateItemid = CreateAttachment(esb, @"c:\\test attachment.txt", iiCreateItemid);

            if(SendMessage(esb,iiCreateItemid))
                Console.WriteLine("Send mail with attachment success!");
            else
                Console.WriteLine("Something error!");

创建会议邀请:

 

 1创建会议邀请邮件
 2     public static void CreateAppointment(ExchangeServiceBinding esb)
 3        {
 4            // Create the appointment.
 5            CalendarItemType appointment = new CalendarItemType();  
 6            // Add item properties to the appointment.
 7            appointment.Body = new BodyType();
 8            appointment.Body.BodyType1 = BodyTypeType.Text;
 9            appointment.Body.Value = "Agenda Items.";
10            //appointment.Categories = new string[] { "Category1", "Category2" };
11            appointment.Importance = ImportanceChoicesType.High;
12            appointment.ImportanceSpecified = true;
13            appointment.ItemClass = "IPM.Appointment";
14            appointment.Subject = "测试约会邮件";
15            // Add an attendee
16            EmailAddressType eat1 = new EmailAddressType();
17            eat1.EmailAddress = "第一个与会者邮箱地址";
18            eat1.Name = "姓名";
19            AttendeeType at1 = new AttendeeType();
20            at1.Mailbox = eat1;
21
22            EmailAddressType eat2 = new EmailAddressType();
23            eat2.EmailAddress = "第一二个与会者邮箱地址";
24            eat2.Name = "姓名";
25            AttendeeType at2 = new AttendeeType();
26            at2.Mailbox = eat2;
27
28            AttendeeType[] rAtt = new AttendeeType[2];
29            rAtt[0= at1;
30            rAtt[1= at2;
31            appointment.RequiredAttendees = rAtt;
32
33            //add meeting room attendee
34            EmailAddressType meetingRoom = new EmailAddressType();
35            meetingRoom.EmailAddress = "会议室邮箱地址";
36            meetingRoom.Name = "会议室名称";
37            AttendeeType meetingType = new AttendeeType();
38            meetingType.Mailbox = meetingRoom;
39            AttendeeType[] meetingTypeList = new AttendeeType[1];
40            meetingTypeList[0= meetingType;
41            appointment.Resources = meetingTypeList;
42            appointment.Location = "会议地点";
43            // Add calendar properties to the appointment.
44            appointment.Start = System.DateTime.Parse("2009-05-25GMT14:00:00Z");
45            appointment.StartSpecified = true;
46            appointment.End = System.DateTime.Parse("2009-05-25GMT15:00:00Z");
47            appointment.EndSpecified = true;
48
49            // Identify the destination folder that will contain the appointment.
50            DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
51            folder.Id = DistinguishedFolderIdNameType.calendar;
52
53            // Create the array of items that will contain the appointment.
54            NonEmptyArrayOfAllItemsType arrayOfItems = new NonEmptyArrayOfAllItemsType();
55            arrayOfItems.Items = new ItemType[1];
56
57            // Add the appointment to the array of items.
58            arrayOfItems.Items[0= appointment;
59
60            // Create the CreateItem request.
61            CreateItemType createItemRequest = new CreateItemType();
62            // The SendMeetingInvitations attribute is required for calendar items.
63            //createItemRequest.SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToNone;
64            createItemRequest.SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToAllAndSaveCopy;
65            createItemRequest.SendMeetingInvitationsSpecified = true;
66            // Add the destination folder to the CreateItem request.
67            createItemRequest.SavedItemFolderId = new TargetFolderIdType();
68            createItemRequest.SavedItemFolderId.Item = folder;
69            // Add the items to the CreateItem request.
70            createItemRequest.Items = arrayOfItems;
71            try
72            {
73                // Send the request and get the response.
74                CreateItemResponseType createItemResponse = esb.CreateItem(createItemRequest);
75                // Get the response messages.
76                ResponseMessageType[] rmta = createItemResponse.ResponseMessages.Items;
77                foreach (ResponseMessageType rmt in rmta)
78                {
79                    ArrayOfRealItemsType itemArray = ((ItemInfoResponseMessageType)rmt).Items;
80                    ItemType[] items = itemArray.Items;
81
82                    // Get the item identifier and change key for each item.
83                    foreach (ItemType item in items)
84                    {
85                        Console.WriteLine("Item identifier: " + item.ItemId.Id);
86                        Console.WriteLine("Item change key: " + item.ItemId.ChangeKey);
87                    }

88                }

89            }

90            catch (Exception e)
91            {
92                Console.WriteLine("Error Message: " + e.Message);
93            }

94        }

应答会议邀请:

 

 1应答会议邀请
 2   public static void AcceptItem(ExchangeServiceBinding esb,string meetingID)
 3         {
 4            // Create the request.
 5            CreateItemType request = new CreateItemType();
 6
 7            // Set the message disposition on the request.
 8            request.MessageDisposition = MessageDispositionType.SendAndSaveCopy;
 9            request.MessageDispositionSpecified = true;
10            
11            // Create the AcceptItem response object.
12            AcceptItemType acceptItem = new AcceptItemType();
13
14            // Identify the meeting request to accept.
15            acceptItem.ReferenceItemId = new ItemIdType();
16            acceptItem.ReferenceItemId.Id = meetingID;
17
18            // Add the AcceptItem response object to the request.
19            request.Items = new NonEmptyArrayOfAllItemsType();
20            request.Items.Items = new ItemType[1];
21            request.Items.Items[0= acceptItem;           
22            // Send the request and get the response.
23            CreateItemResponseType response = esb.CreateItem(request);
24
25            ArrayOfResponseMessagesType aormt = response.ResponseMessages;
26            ResponseMessageType[] rmta = aormt.Items;
27            foreach (ResponseMessageType rmt in rmta)
28            {
29                ItemInfoResponseMessageType iirmt = (rmt as ItemInfoResponseMessageType);
30                if (iirmt.ResponseClass == ResponseClassType.Success)
31                {
32                    Console.WriteLine("Successfully accepted meeting");
33                }

34            }

35        }

           未完待续。。。。

posted on 2009-06-25 16:52  盼盼程序员  阅读(1655)  评论(1编辑  收藏  举报