Office 365 – Exchange Online examples

原文 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.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new WebCredentials("[email protected]", "UserPassword");
service.AutodiscoverUrl("[email protected]", 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.

static bool RedirectionUrlValidationCallback(String redirectionUrl)
{
    bool redirectionValidated = false;
    if (redirectionUrl.Equals(
		"https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml"))
        redirectionValidated = true;
 
    return redirectionValidated;
}

Creating a contact

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

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

static void FindContactsByGivenName()
{
    string search = "John";
    FindItemsResults<Item> foundItems =
        service.FindItems(WellKnownFolderName.Contacts,
			new SearchFilter.IsEqualTo(ContactSchema.GivenName, search),
			new ItemView(5));
 
    foreach (Item item in foundItems)
    {
        if (item is Contact)
        {
            Contact foundContact = (Contact)item;
            Console.WriteLine(String.Format("{0} - {1}",
                foundContact.CompleteName.FullName,
                foundContact.CompanyName));
        }
    }
}

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:

static void FindContactByExtendedProperty()
{
    string search = "SMITHINC";
    ExtendedPropertyDefinition clientIdPropertyDefinition =
        new ExtendedPropertyDefinition(propertySetId, "ClientId",
            MapiPropertyType.String);
 
    FindItemsResults<Item> foundItems =
        service.FindItems(WellKnownFolderName.Contacts,
			new SearchFilter.IsEqualTo(clientIdPropertyDefinition, search),
			new ItemView(5));
 
    foreach (Item item in foundItems)
    {
        if (item is Contact)
        {
            Contact foundContact = (Contact)item;
            Console.WriteLine(String.Format("{0} - {1}",
                foundContact.CompleteName.FullName,
                foundContact.CompanyName));
        }
    }
 
}

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:

static void UpdateContact(string email = "[email protected]")
{
    FindItemsResults<Item> foundItems =
            service.FindItems(WellKnownFolderName.Contacts,
				new SearchFilter.IsEqualTo(ContactSchema.EmailAddress1, email),
				new ItemView(5));
 
    Item foundItem = foundItems.FirstOrDefault();
    if (foundItem != null && foundItem is Contact)
    {
        Contact foundContact = (Contact)foundItem;
        foundContact.JobTitle = "Chief Operating Officer";
        foundContact.Update(ConflictResolutionMode.AutoResolve);
    }
}

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:

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

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:

static void FindEmailBySubject(string subject = "Sending from EWS")
{
    FindItemsResults<Item> foundItems =
        service.FindItems(WellKnownFolderName.Inbox,
			new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, subject),
			new ItemView(5));
 
    foreach (Item item in foundItems)
    {
        if (item is EmailMessage)
        {
            EmailMessage foundEmail = (EmailMessage)item;
            Console.WriteLine("From Address: " + foundEmail.From.Name);
            Console.WriteLine("Received: " +
				foundEmail.DateTimeReceived.ToShortDateString());
            Console.WriteLine("----------------------------");
        }
    }
}

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:

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

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:

static void FindAppointmentsForTodayTomorrow()
{
    FindItemsResults<Appointment> foundAppointments =
        service.FindAppointments(WellKnownFolderName.Calendar,
			new CalendarView(DateTime.Now, DateTime.Now.AddDays(1)));
 
    foreach (Appointment app in foundAppointments)
    {
        Console.WriteLine("Subject: " + app.Subject);
        Console.WriteLine("Start: " + app.Start);
        Console.WriteLine("Duration: " + app.Duration);
        Console.WriteLine("------------------------");
    }
}

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:

static void CreateFolder()
{
    Folder readLaterFolder = new Folder(service);
    readLaterFolder.DisplayName = "Read Later";
    readLaterFolder.Save(WellKnownFolderName.Inbox);
 
    Folder workEmailFolder = new Folder(service);
    workEmailFolder.DisplayName = "Work mail";
    workEmailFolder.Save(readLaterFolder.Id);
}

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:

static void ListFoldersInInbox()
{
    FindFoldersResults findResults = service.FindFolders(WellKnownFolderName.Inbox,
		new FolderView(10));
 
    foreach (Folder folder in findResults.Folders)
    {
        Console.WriteLine(folder.DisplayName);
    }
}

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:

static void SetOutOfOffice()
{
    OofSettings settings = new OofSettings();
    settings.State=OofState.Enabled;
    settings.InternalReply = new OofReply(
		"Hi Team Member, I‘m out on my 2 day break. Back Soon!");
    settings.ExternalReply = new OofReply(
		"Dear Customer, I‘m currently out of the office. " +
		"Please forward all queries to Sam at [email protected]");
    settings.ExternalAudience = OofExternalAudience.Known;
    service.SetUserOofSettings(userEmail,settings);
}

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:

static void GetOutOfOffice()
{
    OofSettings settings = service.GetUserOofSettings(userEmail);
    if (settings.State == OofState.Enabled)
    {
        Console.WriteLine("You are currently OUT of the office");
    }
    else if (settings.State == OofState.Scheduled)
    {
        Console.WriteLine("You are currently OUT of the office and will return on " +
			settings.Duration.EndTime.ToLongDateString());
    }
    else
    {
        Console.WriteLine("You are currently IN the office");
    }
}

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

static void GetAvailability()
{
    List<AttendeeInfo> attendees = new List<AttendeeInfo>();
    attendees.Add(new AttendeeInfo(userEmail));
 
    GetUserAvailabilityResults results =
		service.GetUserAvailability(attendees,
			new TimeWindow(DateTime.Now, DateTime.Now.AddHours(24)),
			AvailabilityData.FreeBusy);
 
    AttendeeAvailability myAvailablity =
		results.AttendeesAvailability.FirstOrDefault();
    if (myAvailablity != null)
    {
        Console.WriteLine(String.Format(
			"You have {0} appointments/meetings in the next 24 hours",
            myAvailablity.CalendarEvents.Count));
    }
}

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

时间: 2024-08-08 09:21:02

Office 365 – Exchange Online examples的相关文章

不同版本的outlook客户端配置Office 365 exchange online帐户需要安装的补丁

近期做了1个关于Office 365混合部署的项目,客户的环境中outlook的版本有outlook2007.outlook2010和outlook2013,目前的Office 365 exchange online是支持这些客户端进行邮箱配置的,但针对outlook2007和2010来说,我们是需要安装一些相关的补丁后才可以实现的. 下面是我在反复测试后确认需要安装的补丁号及下载链接,供大家参考,希望在以后遇到类似的项目时对大家有所帮助. 1       针对office2010 1.1  

Office 365 Exchange E1国际版注册试用(一)

2015年在上一家港资企业,原在香港两台,深圳两台,重庆一台的Exchange Server 2003邮件服务器,由于企业大幅度减人,总邮箱数量由近500个减至200个,而邮件系统又旧,所以就建议公司统一在香港购买了Office365 Exchange Online1,由原来的Exchange server  2003邮件服务器转至到Microsoft Office365 E1,在香港1个邮箱只要港币365元/年,这样,就不用购买邮件服务器License,不用自己维护,不用购买硬件服务器,免几年

Office 365 Exchange E1国际版注册试用(三)-创建邮箱用户

创建邮箱用户. 进入Office365管理界面.在用户-活动用户内,可一个一个增加或从文件进行导入. 单用户添加

Exchange & Office 365最小混合部署

前言 这篇文章的主题是混合部署~ 混合使得本地组织和云环境像一个单一的.协作紧密的组织一样运作.当组织决定进行混合部署,达到本地Exchange Server和Office 365共存的状态时,就会面临一个选择:最小混合部署和完全混合部署. 最小混合部署和完全混合部署适应的情况不同.当组织存在以下情况的时候,我们建议选择最小混合部署,规避掉一些复杂的设置,进行快速迁移: 为用户提供无缝迁移体验的中小型客户 组织不打算将本地的邮箱保留很长时间 组织不希望再运行Azure AD Connect来将用

使用Powershell链接到Office 365

今天主要讲使用Powershell管理Office 365 可以分为office365用户管理,Exchange Online的管理等 1. 使用Powershell 链接到office 365 用户管理界面 需要先安装登陆助手及Azure AD模块 在windows powershell 下运行: Get-ExecutionPolicySet-ExecutionPolicy RemoteSigned //更改执行策略,执行一次就够了$credential = Get-Credential  

易宝典文章——玩转Office 365中的Exchange Online服务 之三十 体验全新的Office 365管理中心

Office 365管理中心即将改版,微软推出了全新的Office 365管理中,其风格和Windows 10风格匹配.接下来将展示一下关于全新的管理中心,以便先睹为快.一.主页和服务状态监视在主页中显示Modern风格的按钮,默认有"用户"."账单"."服务运行状态"等常用功能.特别是对于"服务运行状况",如果是绿色,则表示所有O365的服务运行正常,如果非绿色,可以可能有服务运行问题,可以直接点击"查看服务运行状

易宝典文章——玩转Office 365中的Exchange Online服务 之二 怎样申请一个Office 365企业(试用)账户

玩转Office 365中的Exchange Online服务 之二 怎样申请一个Office 365企业(试用)账户 前面简单介绍了Office 365和Exchange Online.也就是说,可以给客户或公司老板推荐这个产品.但是,需要更有说服力的演示和客户体验才能打动甲方或老板. 对于前期体验和评估来讲,如果直接订阅一个正式版,会带来过高的评估成本,即使是订阅最廉价的版本,往往在企业采购前期评估中也会是困难重重,很多时候会直接导致项目的夭折. 幸运的是,对于Office 365来讲,可以

易宝典文章——玩转Office 365中的Exchange Online服务 之三 了解Office 365管理中心

继续前面的话题,现在已经有了Office 365的环境.可以很轻松的向甲方客户或公司老板进行展示了.但是在展示之前,首先要自己先对Office 365进行深入的了解和试用,否则在Q&A环节会被问得体无完肤.所以,对于Office 365的基本管理必须熟练掌握.接下来的内容将对Office 365的管理工具进行简单的浏览,以便更好的为后续的Exchange Online的管理提供基础. 一.登录到Office 365主页 世纪互联版的Office 365可以通过以下URL进行登录: http://

易宝典文章——玩转Office 365中的Exchange Online服务 之四 在Office 365中怎样自定义域

现在已经对Office 365的管理有一定基础了,接下来的首要任务就是正名,所谓"名不正,言不顺".在订阅Office 365的时候,需要创建一个订阅ID,即默认管理员的账号.在创建这个订阅ID时,需要指定一个域名后缀,该域名后缀是基于同一的Office 365用户域的一个子域.其形式如下: [email protected]提醒您,请勿滥发广告! partner.onm51CTO提醒您,请勿滥发广告!是不能更改的,这是世纪互联版Office 365用户专用的域: XXXXXX可以由于