Trabalhando com Regras no Exchange Server

Gerenciando Regras

Aspose.Email pode ser usado para gerenciar as regras no Exchange Server usando o EWSClient classe. Esta classe usa o Exchange Web Services (EWS), que está disponível no Exchange Server 2007 e versões posteriores. Para mostrar como gerenciar regras, este artigo explica como:

  • Ler as regras já existentes no servidor.
  • Criar uma nova regra.
  • Atualizar uma regra existente.

Microsoft Exchange Server 2010 Service Pack 1 é necessário para todos os recursos descritos neste artigo.

Uma regra é representada por um InboxRule objeto. Suas condições são mantidas em um RulePredicates objeto – por exemplo os remetentes ou as palavras que o assunto deve conter – e suas ações em um RuleActions objeto – por exemplo a pasta para onde mover a mensagem.

Os exemplos neste artigo usam esses cabeçalhos e namespaces:

#include <MailAddress.h>
#include <MailAddressCollection.h>
#include <Clients/Exchange/WebService/EWSClient/EWSClient.h>
#include <Clients/Exchange/WebService/EWSClient/IEWSClient.h>
#include <Clients/Exchange/InboxRules/InboxRule.h>
#include <Clients/Exchange/InboxRules/RulePredicates.h>
#include <Clients/Exchange/InboxRules/RuleActions.h>
#include <system/array.h>
#include <system/collections/specialized/string_collection.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Clients::Exchange;
using namespace Aspose::Email::Clients::Exchange::WebService;

Ler Regras

Para obter todas as regras do Exchange Server:

  1. Conectar a um Exchange Server usando o IEWSClient classe.
  2. Chame o IEWSClient->GetInboxRules() método para obter todas as regras.
  3. Em um loop, percorra todas as regras e exiba as propriedades da regra, como condições, ações e nomes.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

try
{
    for (SharedPtr<InboxRule> inboxRule : client->GetInboxRules())
    {
        Console::WriteLine(u"Display Name: " + inboxRule->get_DisplayName());

        // The "From Address" condition
        for (SharedPtr<MailAddress> fromAddress : inboxRule->get_Conditions()->get_FromAddresses())
        {
            Console::WriteLine(u"From: " + fromAddress->get_DisplayName() + u" - " + fromAddress->get_Address());
        }

        // The "Subject Contains" condition
        SharedPtr<Collections::Specialized::StringCollection> subjectStrings = inboxRule->get_Conditions()->get_ContainsSubjectStrings();
        for (int32_t i = 0; i < subjectStrings->get_Count(); i++)
        {
            Console::WriteLine(u"Subject contains: " + subjectStrings->idx_get(i));
        }

        // The "Move to Folder" action
        if (!String::IsNullOrEmpty(inboxRule->get_Actions()->get_MoveToFolder()))
        {
            Console::WriteLine(u"Move message to folder: " + inboxRule->get_Actions()->get_MoveToFolder());
        }
    }
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();

Criando uma Nova Regra

Para criar uma nova regra no Exchange Server, siga os passos abaixo:

  1. Conectar a um Exchange Server usando o IEWSClient classe.
  2. Crie uma nova instância da InboxRule classe e definir as seguintes propriedades obrigatórias:
    1. NomeExibido
    2. Condições
    3. Ações
  3. Chame o IEWSClient->CreateInboxRule() método para criar a regra.

A regra abaixo move as mensagens de um remetente específico cujo assunto contém "ABC" para outra pasta. A pasta é identificada pelo seu ID, que faz parte das informações da pasta retornadas pelo cliente. O segundo argumento do MailAddress construtor, true, ignora a verificação de sintaxe do endereço.

SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

SharedPtr<InboxRule> rule = MakeObject<InboxRule>();
rule->set_DisplayName(u"Message from client ABC");

// Conditions: the subject contains "ABC" and the message comes from the given sender
SharedPtr<RulePredicates> conditions = MakeObject<RulePredicates>();
conditions->get_ContainsSubjectStrings()->Add(u"ABC");
conditions->get_FromAddresses()->Add(MakeObject<MailAddress>(u"administrator@ex2010.local", true));
rule->set_Conditions(conditions);

// Action: move the message to a folder
SharedPtr<RuleActions> actions = MakeObject<RuleActions>();
actions->set_MoveToFolder(u"120:AAMkADFjMjNjMmNjLWE3NzgtNGIzNC05OGIyLTAwNTgzNjRhN2EzNgAuAAAAAABbwP+Tkhs0TKx1GMf0D/cPAQD2lptUqri0QqRtJVHwOKJDAAACL5KNAAA=AQAAAA==");
rule->set_Actions(actions);

try
{
    client->CreateInboxRule(rule);
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();

Atualizando uma Regra

Para atualizar uma regra no Exchange Server:

  1. Conectar a um Exchange Server usando o IEWSClient classe.
  2. Chame o IEWSClient->GetInboxRules() método para obter todas as regras.
  3. Em um loop, navegue por todas as regras e encontre a regra que deseja alterar pelo nome exibido.
  4. Atualizar as propriedades da regra.
  5. Chame o IEWSClient->UpdateInboxRule() método para atualizar a regra.

O exemplo substitui o primeiro endereço do remetente da regra criada acima.

SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

for (SharedPtr<InboxRule> inboxRule : client->GetInboxRules())
{
    Console::WriteLine(u"Display Name: " + inboxRule->get_DisplayName());
    if (inboxRule->get_DisplayName() == u"Message from client ABC")
    {
        Console::WriteLine(u"Updating the rule....");
        inboxRule->get_Conditions()->get_FromAddresses()->idx_set(0, MakeObject<MailAddress>(u"administrator@ex2010.local", true));
        client->UpdateInboxRule(inboxRule);
    }
}

client->Dispose();