Работа с правилами на Exchange Server

Управление правилами

Aspose.Email для .NET может быть использован для управления правилами на Exchange Server с использованием класса EWSClient. Этот класс использует Exchange Web Services (EWS), которые доступны в Exchange Server 2007 и более поздних версиях. В этой статье объясняется, как управлять правилами:

  • Чтение правил, уже находящихся на сервере.
  • Создание нового правила.
  • Обновление существующего правила.

Для всех функций, описанных в этой статье, требуется Microsoft Exchange Server 2010 Service Pack 1.

Чтение правил

Чтобы получить все правила с Exchange Server:

  1. Подключитесь к Exchange Server с использованием класса IEWSClient.
  2. Вызовите метод IEWSClient.GetInboxRules(), чтобы получить все правила.
  3. В цикле foreach просмотрите все правила и отобразите свойства правила, такие как условия, действия и имя.

Следующий фрагмент кода показывает, как читать правила.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Set mailboxURI, Username, password, domain information
string mailboxURI = "https://ex2010/ews/exchange.asmx";
string username = "test.exchange";
string password = "pwd";
string domain = "ex2010.local";
// Connect to the Exchange Server
NetworkCredential credential = new NetworkCredential(username, password, domain);
IEWSClient client = EWSClient.GetEWSClient(mailboxURI, credential);
Console.WriteLine("Connected to Exchange server");
// Get all Inbox Rules
InboxRule[] inboxRules = client.GetInboxRules();
// Display information about each rule
foreach (InboxRule inboxRule in inboxRules)
{
Console.WriteLine("Display Name: " + inboxRule.DisplayName);
// Check if there is a "From Address" condition
if (inboxRule.Conditions.FromAddresses.Count > 0)
{
foreach (MailAddress fromAddress in inboxRule.Conditions.FromAddresses)
{
Console.WriteLine("From: " + fromAddress.DisplayName + " - " + fromAddress.Address);
}
}
// Check if there is a "Subject Contains" condition
if (inboxRule.Conditions.ContainsSubjectStrings.Count > 0)
{
foreach (String subject in inboxRule.Conditions.ContainsSubjectStrings)
{
Console.WriteLine("Subject contains: " + subject);
}
}
// Check if there is a "Move to Folder" action
if (inboxRule.Actions.MoveToFolder.Length > 0)
{
Console.WriteLine("Move message to folder: " + inboxRule.Actions.MoveToFolder);
}
}

Создание нового правила

Чтобы создать новое правило на Exchange Server, выполните следующие шаги:

  1. Подключитесь к Exchange Server с использованием интерфейса IEWSClient.
  2. Создайте новый экземпляр класса InboxRule и установите следующие обязательные свойства:
    1. DisplayName
    2. Conditions
    3. Actions
  3. Вызовите метод IEWSClient.CreateInboxRule(), чтобы создать правило.

Следующий фрагмент кода показывает, как создать новое правило.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Set Exchange Server web service URL, Username, password, domain information
string mailboxURI = "https://ex2010/ews/exchange.asmx";
string username = "test.exchange";
string password = "pwd";
string domain = "ex2010.local";
// Connect to the Exchange Server
NetworkCredential credential = new NetworkCredential(username, password, domain);
IEWSClient client = EWSClient.GetEWSClient(mailboxURI, credential);
Console.WriteLine("Connected to Exchange server");
InboxRule rule = new InboxRule();
rule.DisplayName = "Message from client ABC";
// Add conditions
RulePredicates newRules = new RulePredicates();
// Set Subject contains string "ABC" and Add the conditions
newRules.ContainsSubjectStrings.Add("ABC");
newRules.FromAddresses.Add(new MailAddress("administrator@ex2010.local", true));
rule.Conditions = newRules;
// Add Actions and Move the message to a folder
RuleActions newActions = new RuleActions();
newActions.MoveToFolder = "120:AAMkADFjMjNjMmNjLWE3NzgtNGIzNC05OGIyLTAwNTgzNjRhN2EzNgAuAAAAAABbwP+Tkhs0TKx1GMf0D/cPAQD2lptUqri0QqRtJVHwOKJDAAACL5KNAAA=AQAAAA==";
rule.Actions = newActions;
client.CreateInboxRule(rule);

Обновление правила

Чтобы обновить правило на Exchange Server:

  1. Подключитесь к Exchange Server с использованием класса IEWSClient.
  2. Вызовите метод IEWSClient.GetInboxRules(), чтобы получить все правила.
  3. В цикле foreach просмотрите все правила и получите правило, которое вы хотите изменить, сопоставив DisplayName в условии.
  4. Обновите свойства правила.
  5. Вызовите метод IEWSClient.UpdateInboxRule() для обновления правила.

Следующий фрагмент кода показывает, как обновить правило.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Set mailboxURI, Username, password, domain information
string mailboxURI = "https://ex2010/ews/exchange.asmx";
string username = "test.exchange";
string password = "pwd";
string domain = "ex2010.local";
// Connect to the Exchange Server
NetworkCredential credential = new NetworkCredential(username, password, domain);
IEWSClient client = EWSClient.GetEWSClient(mailboxURI, credential);
Console.WriteLine("Connected to Exchange server");
// Get all Inbox Rules
InboxRule[] inboxRules = client.GetInboxRules();
// Loop through each rule
foreach (InboxRule inboxRule in inboxRules)
{
Console.WriteLine("Display Name: " + inboxRule.DisplayName);
if (inboxRule.DisplayName == "Message from client ABC")
{
Console.WriteLine("Updating the rule....");
inboxRule.Conditions.FromAddresses[0] = new MailAddress("administrator@ex2010.local", true);
client.UpdateInboxRule(inboxRule);
}
}