原文 Office 365 – Exchange Online examples

2012 is upon us and here’s wishing you all a very happy and prosperous new year! Last year we’ve taken a quick look at What Exchange Online extensibility is and what you can use it for, and in today’s post we’ll take a bit more of a hands-on approach and look at some examples of performing various tasks in Exchange Online using the Exchange Web Services API.

Let’s jump straight into some code by creating a new console application in Visual Studio 2010:

Add a reference to Microsoft.Exchange.WebServices.dll, you’ll find it the C:\Program Files\Microsoft\Exchange\Web Services\1.1 folder. If you do not have the Microsoft.Exchange.WebServices dll, you probably do not have the Exchange Web Services Managed API installed. You can download it from the Microsoft Download Center.

Connecting to the Exchange Service

Before you can perform any task or run any queries against Exchange Online, you need to connect to the Exchange Online service. To do this you use the ExchangeService object.

  1. ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
  2. service.Credentials = new WebCredentials("user@domain.com", "UserPassword");
  3. service.AutodiscoverUrl("user@domain.com", RedirectionUrlValidationCallback);

Although the AutodiscoverUrl method has a constructor that only takes the user’s e-mail address; it will always throw an exception if the validateRedirectionUrlCallback parameter is not specified. The RedirectionUrlValidationCallback method should verify that the redirection address is valid and as a best practise, should never return true unconditionally.

  1. static bool RedirectionUrlValidationCallback(String redirectionUrl)
  2. {
  3. bool redirectionValidated = false;
  4. if (redirectionUrl.Equals(
  5. "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml"))
  6. redirectionValidated = true;
  7.  
  8. return redirectionValidated;
  9. }

Creating a contact

With the serviced code in place, we can now create a contact with the following code:

  1. // Create the Contact
  2. Contact newContact = new Contact(service);
  3. newContact.GivenName = "John";
  4. newContact.Surname = "Smith";
  5. newContact.FileAsMapping = FileAsMapping.GivenNameSpaceSurname;
  6. newContact.CompanyName = "Smith & Smith Inc.";
  7. newContact.JobTitle = "CEO";
  8. newContact.AssistantName = "Pocahontas";
  9. newContact.Body = "Captain John Smith (c. January 1580 – 21 June 1631) Admiral " +
  10. "of New England was an English soldier, explorer, and author. He was knighted " +
  11. "for his services to Sigismund Bathory, Prince of Transylvania and friend Mozes Szekely.";
  1. // Add E-mail Addresses
  2. EmailAddress contactEmail1 = new EmailAddress("Work", "johnS@s-and-s.com");
  3. EmailAddress contactEmail2 = new EmailAddress("Home", "john@gmail.com");
  4. newContact.EmailAddresses[EmailAddressKey.EmailAddress1] = contactEmail1;
  5. newContact.EmailAddresses[EmailAddressKey.EmailAddress2] = contactEmail2;
  1. //Add Contact Photo
  2. FileAttachment contactPhoto =
  3. newContact.Attachments.AddFileAttachment(@"C:\Temp\JohnSmith.png");
  4. contactPhoto.IsContactPhoto = true;
  1. //Add Extended Property
  2. Guid propertySetId = new Guid("{F4FD924D-5489-4AE1-BD43-25491342529B}");
  3. ExtendedPropertyDefinition clientIdPropertyDefinition =
  4. new ExtendedPropertyDefinition(propertySetId, "ClientId", MapiPropertyType.String);
  5. newContact.SetExtendedProperty(clientIdPropertyDefinition, "SMITHINC");
  6.  
  7. newContact.Save();

The code will seem familiar if you worked with the Outlook Object model before. However, there are a number of differences: in the first part of the method, we set the standard Exchange properties. We then add 2 e-mail addresses to the contact; each e-mail address can have a descriptive name.

Next, an image is added to the contact as a file attachment. Setting the IsContactPhoto property to true will set the attached file as the contact’s picture. Finally, we add an extended property to the contact. A GUID is declared as the propertySetId, this only needs to be declared once and should be reused when accessing the extended property. You can define one property set identifier and use it for all the extended properties that get read or written to throughout your application.

When you run this code you should see the new contact in the Outlook Web app:

If you need to create a new contact in Outlook, see this post How to create a new Outlook Contact item programmatically.

Finding contacts by name

To search for a contact in Exchange Online use the following code:

  1. static void FindContactsByGivenName()
  2. {
  3. string search = "John";
  4. FindItemsResults<Item> foundItems =
  5. service.FindItems(WellKnownFolderName.Contacts,
  6. new SearchFilter.IsEqualTo(ContactSchema.GivenName, search),
  7. new ItemView(5));
  8.  
  9. foreach (Item item in foundItems)
  10. {
  11. if (item is Contact)
  12. {
  13. Contact foundContact = (Contact)item;
  14. Console.WriteLine(String.Format("{0} - {1}",
  15. foundContact.CompleteName.FullName,
  16. foundContact.CompanyName));
  17. }
  18. }
  19. }

In the above code, we created a new FindItemResults collection and set it equal to the return value of the services’ FindItems method. The FindItems method accepts three parameters:

  • the first is an enumeration value specifying which folder to search;
  • the second is a new instance of a SearchFilter object, where we specify on what criteria we want to search; and
  • lastly we pass in a new instance of an ItemView object where we set the number of records to return. We then loop through the foundItems collection and print the contact details.

Finding contacts by Extended property

You can also search for an item based on the values in an extended property:

  1. static void FindContactByExtendedProperty()
  2. {
  3. string search = "SMITHINC";
  4. ExtendedPropertyDefinition clientIdPropertyDefinition =
  5. new ExtendedPropertyDefinition(propertySetId, "ClientId",
  6. MapiPropertyType.String);
  7.  
  8. FindItemsResults<Item> foundItems =
  9. service.FindItems(WellKnownFolderName.Contacts,
  10. new SearchFilter.IsEqualTo(clientIdPropertyDefinition, search),
  11. new ItemView(5));
  12.  
  13. foreach (Item item in foundItems)
  14. {
  15. if (item is Contact)
  16. {
  17. Contact foundContact = (Contact)item;
  18. Console.WriteLine(String.Format("{0} - {1}",
  19. foundContact.CompleteName.FullName,
  20. foundContact.CompanyName));
  21. }
  22. }
  23.  
  24. }

The above code is similar to searching for a contact by name except that we first declare a reference to the extended property we’ve created earlier. You’ll notice we’re reusing the Property Set Id which was declared earlier. We then pass the clientIdPropertyDefinition as a parameter for the SearchFilter. The result is a list of all contacts whose ClientId extended property has a value of "SMITHINC"

Updating contacts

Update the contact with the following code:

  1. static void UpdateContact(string email = "johnS@s-and-s.com")
  2. {
  3. FindItemsResults<Item> foundItems =
  4. service.FindItems(WellKnownFolderName.Contacts,
  5. new SearchFilter.IsEqualTo(ContactSchema.EmailAddress1, email),
  6. new ItemView(5));
  7.  
  8. Item foundItem = foundItems.FirstOrDefault();
  9. if (foundItem != null && foundItem is Contact)
  10. {
  11. Contact foundContact = (Contact)foundItem;
  12. foundContact.JobTitle = "Chief Operating Officer";
  13. foundContact.Update(ConflictResolutionMode.AutoResolve);
  14. }
  15. }

The code above first searches for a contact by e-mail address, if the contact is found we set the JobTitleproperty and call the Update method on the Contact object. The Update method accepts an enumeration parameter ConflictResolutionMode. Possible values for the parameter are:

  • ConflictResolution.AlwaysOverwrite – Any local property changes will overwrite any server-side changes.
  • ConflictResolution.AutoResolve – Unless the server-side copy is more recent than the local copy, its values will be overwritten by any local property changes.
  • ConflictResolution.NeverOverwrite – All local property changes are discarded.

If you compiled the code and ran it again, you would be able to see that John Smith’s Job Title has changed.

Creating and sending an e-mail message

Creating and sending an e-mail is also similar to the Outlook object model:

  1. static void CreateAndSendEmail()
  2. {
  3. EmailMessage email = new EmailMessage(service);
  4. email.ToRecipients.Add(new EmailAddress(userEmail));
  5. email.Subject = "Sending from EWS";
  6. email.Body = "Hi There, this was sent using Exchange Web Services. Pretty neat!";
  7.  
  8. email.Attachments.AddFileAttachment(@"C:\Temp\JohnSmith.png");
  9. email.SendAndSaveCopy();
  10. }

In the code above, we created a new e-mail message and added an EmailAddress object to its ToRecipientscollection. Adding an attachment is done in a similar fashion as with the contact previously. When you want to send the e-mail you have a choice between two methods on the EmailMessage object: Send orSendAndSaveCopy. The SendAndSaveCopy method sends the e-mail and saves a copy of it to the Sent Items folder. The Send method sends the e-mail and does not store a copy of it.

Once your e-mail is sent, you should see it in your Office 365 Outlook Inbox.

If you need to create and send an e-mail in Outlook, see this post How to create and send an Outlook message programmatically.

Finding e-mails by subject

Finding email is similar to searching for contacts:

  1. static void FindEmailBySubject(string subject = "Sending from EWS")
  2. {
  3. FindItemsResults<Item> foundItems =
  4. service.FindItems(WellKnownFolderName.Inbox,
  5. new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, subject),
  6. new ItemView(5));
  7.  
  8. foreach (Item item in foundItems)
  9. {
  10. if (item is EmailMessage)
  11. {
  12. EmailMessage foundEmail = (EmailMessage)item;
  13. Console.WriteLine("From Address: " + foundEmail.From.Name);
  14. Console.WriteLine("Received: " +
  15. foundEmail.DateTimeReceived.ToShortDateString());
  16. Console.WriteLine("----------------------------");
  17. }
  18. }
  19. }

The only difference between this code and searching for contacts is the WellKnowFolderName and theSearchFilter‘s parameter.

For an Outlook sample, see How to use Find and FindNext methods to retrieve Outlook mail items.

Creating appointments

To create an appointment in the default calendar use the following code:

  1. static void CreateAppointment()
  2. {
  3. Appointment app = new Appointment(service);
  4. app.Subject = "Meet George";
  5. app.Body = "You need to meet George";
  6. app.Location = "1st Floor Boardroom";
  7. app.Start = DateTime.Now.AddHours(2);
  8. app.End = DateTime.Now.AddHours(3);
  9. app.IsReminderSet = true;
  10. app.ReminderMinutesBeforeStart = 15;
  11. app.RequiredAttendees.Add(new Attendee(userEmail));
  12. app.Save(SendInvitationsMode.SendToAllAndSaveCopy);
  13. }

This code creates an appointment in the default calendar and sends a meeting request to the logged-in user. The Save method accepts the SendInvitationsMode enumeration as parameter and possible values for this are:

  • SendInvitationsMode.SendOnlyToAll – Sends meeting invitations to all attendees, but does not save a copy of the meeting invitation in the organizer’s Sent Items folder.
  • SendInvitationsMode.SendToAllAndSaveCopy – Will send the meeting invitation to all attendees and save a copy of it in the organizer’s Sent Items folder.
  • SendInvitationsMode.SendToNone – Will not send any meeting invitations.

Once created you should see the meeting in your Office 365 Outlook Calendar.

If you develop for Outlook, see How to create a new Outlook Appointment item.

Find appointments for today and tomorrow

To find any appointments for today and tomorrow you can use the following code:

  1. static void FindAppointmentsForTodayTomorrow()
  2. {
  3. FindItemsResults<Appointment> foundAppointments =
  4. service.FindAppointments(WellKnownFolderName.Calendar,
  5. new CalendarView(DateTime.Now, DateTime.Now.AddDays(1)));
  6.  
  7. foreach (Appointment app in foundAppointments)
  8. {
  9. Console.WriteLine("Subject: " + app.Subject);
  10. Console.WriteLine("Start: " + app.Start);
  11. Console.WriteLine("Duration: " + app.Duration);
  12. Console.WriteLine("------------------------");
  13. }
  14. }

The code is similar to finding e-mails or contacts, except the FindItemsResults collection contains anAppointment object and we used the FindAppointments method of the ExchangeService object to find the appointments. The filter is applied using a CalendarView object.

Creating folders

Creating folders in Exchange online can easily be done using the code below:

  1. static void CreateFolder()
  2. {
  3. Folder readLaterFolder = new Folder(service);
  4. readLaterFolder.DisplayName = "Read Later";
  5. readLaterFolder.Save(WellKnownFolderName.Inbox);
  6.  
  7. Folder workEmailFolder = new Folder(service);
  8. workEmailFolder.DisplayName = "Work mail";
  9. workEmailFolder.Save(readLaterFolder.Id);
  10. }

You can create a folder by declaring a new Folder object and setting its DisplayName property. The Savemethods required the parent folder to be specified, you can pass in a WellKnownFolderName enumeration value or an existing folders’ Id.

You will notice two new folders in your Office 365 Outlook:

List Inbox sub-folders

To list the sub-folders in the Inbox use the following code:

  1. static void ListFoldersInInbox()
  2. {
  3. FindFoldersResults findResults = service.FindFolders(WellKnownFolderName.Inbox,
  4. new FolderView(10));
  5.  
  6. foreach (Folder folder in findResults.Folders)
  7. {
  8. Console.WriteLine(folder.DisplayName);
  9. }
  10. }

In the code above we declare a FindFoldersResults object and set it equal to the return value of the FindFolders method on the ExchangeService object. The FindFolders method accepts either aWellKnownFolderName enumeration value or the Id of an existing folder.

Out of office

Exchange web services allow you not only to create and edit Exchange items but also to leverage its business logic. For example the following code will enable the specified user’s Out of office message:

  1. static void SetOutOfOffice()
  2. {
  3. OofSettings settings = new OofSettings();
  4. settings.State=OofState.Enabled;
  5. settings.InternalReply = new OofReply(
  6. "Hi Team Member, I'm out on my 2 day break. Back Soon!");
  7. settings.ExternalReply = new OofReply(
  8. "Dear Customer, I'm currently out of the office. " +
  9. "Please forward all queries to Sam at sam@s-and-s.com");
  10. settings.ExternalAudience = OofExternalAudience.Known;
  11. service.SetUserOofSettings(userEmail,settings);
  12. }

By setting the State property you either enable or disable the Out of Office notification, setting it to Scheduled and specifying the Duration allow you to schedule the Out of Office notification for a later date. You also have the choice to specify different messages for internal or external addresses as well as which audience to send the response to.

You can not only set the user’s Out of Office status but can also get another user’s Out of Office status by using the following code:

  1. static void GetOutOfOffice()
  2. {
  3. OofSettings settings = service.GetUserOofSettings(userEmail);
  4. if (settings.State == OofState.Enabled)
  5. {
  6. Console.WriteLine("You are currently OUT of the office");
  7. }
  8. else if (settings.State == OofState.Scheduled)
  9. {
  10. Console.WriteLine("You are currently OUT of the office and will return on " +
  11. settings.Duration.EndTime.ToLongDateString());
  12. }
  13. else
  14. {
  15. Console.WriteLine("You are currently IN the office");
  16. }
  17. }

Availability

You can also check a users’ availability using the EWS API. In the following example I used theGetUserAvailability method of the ExchangeService object to get an AttendeeAvailability object

  1. static void GetAvailability()
  2. {
  3. List<AttendeeInfo> attendees = new List<AttendeeInfo>();
  4. attendees.Add(new AttendeeInfo(userEmail));
  5.  
  6. GetUserAvailabilityResults results =
  7. service.GetUserAvailability(attendees,
  8. new TimeWindow(DateTime.Now, DateTime.Now.AddHours(24)),
  9. AvailabilityData.FreeBusy);
  10.  
  11. AttendeeAvailability myAvailablity =
  12. results.AttendeesAvailability.FirstOrDefault();
  13. if (myAvailablity != null)
  14. {
  15. Console.WriteLine(String.Format(
  16. "You have {0} appointments/meetings in the next 24 hours",
  17. myAvailablity.CalendarEvents.Count));
  18. }
  19. }

There you have it, a crash course in some of the functionality available to you as developer when using Exchange Web services with Office 365. Please see the attached sample project for the code to all the above examples.

Thank you for reading. Until next time, keep coding!

Available downloads:

C# sample project

Office 365 – Exchange Online examples的更多相关文章

  1. Exchange & Office 365最小混合部署

    前言 这篇文章的主题是混合部署~ 混合使得本地组织和云环境像一个单一的.协作紧密的组织一样运作.当组织决定进行混合部署,达到本地Exchange Server和Office 365共存的状态时,就会面 ...

  2. 使用Powershell链接到Office 365

    今天主要讲使用Powershell管理Office 365 可以分为office365用户管理,Exchange Online的管理等 1. 使用Powershell 链接到office 365 用户 ...

  3. 准备使用 Office 365 中国版--邮箱迁移

    微软产品一贯的作风是从来不缺文档和教程,Office 365也不例外.无论是最终用户还是企业IT管理员,都可参照Office 365使用指南顺利的开启Office 365之旅.不过比较奇怪的是,貌似很 ...

  4. 启用MFA的office 365 账号如何连接Exchange online

    第一篇随手笔记,从简单开始... 如何使用Exchange Online PowerShell呢? 以Windows操作系统为例,如Windows10:首先需要安装Exchange Online Po ...

  5. Office 365常见问题解答(第一期)

    前不久进行的一次网络调查中,有不少朋友反馈了一些对于Office 365的实际问题,这里集中地做一个解答,请大家参考 1. Office 365的UI样式是否有开源计划 据我所知已经开源了:https ...

  6. Office 365 系列五 -------- Imap邮箱迁移步骤

    当客户购买了我们的Office 365之后,第一个功能必然是会用我们的企业邮箱,如果企业之前是用 263.腾讯.网易等的邮件厂商的话,必然会涉及到邮件的迁移, 其实说到邮箱迁移,我们办法很多,如果人数 ...

  7. Office 365 系列四 ------ 绑定公司域名

    Office 365包含了企业邮箱服务(Exchange Online),我们如果要用微软的企业邮箱,那么我们必须绑定我们公司的自己域名,而不是用微软 提供的二级域名,其实微软的整个Exchange ...

  8. Windows 商店应用中使用 Office 365 API Tools

    本篇我们介绍一个API 工具,用于在 Windows Store App 中使用 Office 365 API. 首先来说一下本文的背景: 使用 SharePoint 做过开发的同学们应该都知道,Sh ...

  9. 准备使用 Office 365 中国版--购买

    Office 365中国版支持两种购买方式,Web Direct(在线购买)和CSP(代理商购买).如果客户的企业规模不大(几十个用户,小于100用户)或者是个人/家庭购买,可以直接选择在线购买方式. ...

随机推荐

  1. Java中的逆变与协变(转)

    看下面一段代码 Number num = new Integer(1); ArrayList<Number> list = new ArrayList<Integer>(); ...

  2. Web Design 再生:UX Design

    高质量的Web 模板,成熟的Design Pattern,人工智能的引用,移动技术的冲击是否标志着Web Design 结束的时代已经到来? Web Design 最终也未避免与“死亡”这个词的关联, ...

  3. SQLServer 2012异常问题(二)--由安装介质引发性能问题

    原文:SQLServer 2012异常问题(二)--由安装介质引发性能问题 问题描述:生产环境一个数据库从SQLSERVER 2008 R2升级到SQLSERVER 2012 ,同时更换硬件,但迁移后 ...

  4. MoveWindow and SetWindowPos

    转自:http://blog.sina.com.cn/s/blog_82c346de0100u7kq.html MoveWindow and SetWindowPos (2011-09-14 15:5 ...

  5. ExtJS4 动态生成grid出口excel(纯粹的接待)

    搜索相当长的时间,寻找一些样本,因为我刚开始学习的原因,大多数人不知道怎么用.. 他曾在源代码.搞到现在终于实现了主下载.. 表的采集格不重复下载一个小BUG,一个使用grid初始化发生的BUG 以下 ...

  6. Upgrade Ver 4.3.x from 4.2.x

    级到遇到个小问题.解决细节记录例如以下. [gpadmin@wx60 ~]$ gpmigrator /usr/local/greenplum-db-4.2.7.2 /usr/local/greenpl ...

  7. Hadoop2.3.0具体安装过程

    前言:       Hadoop实现了一个分布式文件系统(Hadoop Distributed File System),简称HDFS.HDFS有高容错性的特点,并且设计用来部署在低廉的(low-co ...

  8. 【iOS】多线程GCD

    GCD(Grand Central Dispatch) : 牛逼的中枢调度器.苹果自带,纯C语言实现,提供了许多且强大的函数,它能够提高代码的运行效率与多核的利用率. 一.GCD的基本使用 1.GCD ...

  9. Android——保存并读取文件

    Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,仅仅能被应用本身訪问,在该模式下,写入的内容会覆盖原文件的内容,假设想把新写入的内容追加到原文件里.能够使用Contex ...

  10. Linux了解进程的地址空间

    供Linux了解虚拟内存,非常好的引导了.原文链接:http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=26683523&i ...