Funciones de utilidad

Este artículo recopila varias características más pequeñas del cliente EWS: envío de encuestas, aceptación de certificados de servidor que fallan la validación, respuesta y reenvío de mensajes en el servidor, adición de cabeceras a solicitudes EWS, mensajería unificada y consejos de correo.

Los ejemplos en este artículo usan estos encabezados y espacios de nombres:

#include <MailMessage.h>
#include <MailAddress.h>
#include <MailAddressCollection.h>
#include <Attachment.h>
#include <AttachmentCollection.h>
#include <Mapi/FollowUpOptions.h>
#include <Clients/Exchange/WebService/EWSClient/EWSClient.h>
#include <Clients/Exchange/WebService/EWSClient/IEWSClient.h>
#include <Clients/Exchange/WebService/UnifiedMessaging/UnifiedMessagingConfiguration.h>
#include <Clients/Exchange/WebService/MailTips/GetMailTipsOptions.h>
#include <Clients/Exchange/WebService/MailTips/MailTips.h>
#include <Clients/Exchange/WebService/MailTips/MailTipsType.h>
#include <Clients/Exchange/WebService/MailTips/OutOfOfficeMailTip.h>
#include <Clients/Exchange/WebService/MailTips/ReplyBody.h>
#include <Clients/Exchange/ExchangeMailboxInfo.h>
#include <Clients/Exchange/ExchangeMessageInfo.h>
#include <Clients/Exchange/ExchangeMessageInfoCollection.h>
#include <net/service_point_manager.h>
#include <net/secure_protocols/ssl_stream.h>
#include <system/array.h>
#include <system/convert.h>

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

Enviando un mensaje con opción de votación

Microsoft Outlook permite a los usuarios crear una encuesta al redactar un nuevo mensaje añadiendo botones de votación como Sí, No y Tal vez. El FollowUpOptions la clase contiene estos botones en su VotingButtons propiedad, como una lista separada por punto y coma.

Crear y enviar un mensaje con opciones de votación

La sobrecarga de Enviar que toma un FollowUpOptions el objeto envía el mensaje a través de Exchange con los botones de votación adjuntos, de modo que los destinatarios los vean en Outlook.

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

String address = u"firstname.lastname@example.com";
SharedPtr<MailMessage> message = MakeObject<MailMessage>(address, address, u"Flagged message",
    u"Make it nice and short, but descriptive.");

SharedPtr<FollowUpOptions> options = MakeObject<FollowUpOptions>();
options->set_VotingButtons(u"Yes;No;Maybe;Exactly!");

try
{
    client->Send(message, options);
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();

Ignorar o Omitir Certificado SSL Inválido o Expirado

Cuando el certificado del servidor Exchange ha expirado o no se puede validar - típico en servidores de prueba con certificados autofirmados - la conexión falla con una excepción. Una devolución de llamada de validación registrada con System::Net::ServicePointManager decides sobre dichos certificados; una devolución de llamada que siempre devuelve true los acepta. Regístrelo una vez, antes de la primera solicitud, y solo en entornos en los que confíe: desactiva la protección contra servidores impostores.

// Accepts every server certificate, whatever the validation result
static bool AcceptAllCertificates(SharedPtr<Object> sender,
    SharedPtr<Security::Cryptography::X509Certificates::X509Certificate> certificate,
    SharedPtr<Security::Cryptography::X509Certificates::X509Chain> chain,
    Net::Security::SslPolicyErrors sslPolicyErrors)
{
    return true;
}
Net::ServicePointManager::set_ServerCertificateValidationCallback(
    Net::Security::RemoteCertificateValidationCallback(AcceptAllCertificates));

SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://exchange.test.local/ews/exchange.asmx", u"username", u"password");
client->Dispose();

Creando mensajes RE y FW a partir de archivos MSG

IEWSClient permite a los desarrolladores crear mensajes RE (Responder/Responder a todos) y FW (Reenviar) a partir de un mensaje almacenado en el servidor. El mensaje origen se identifica mediante un ExchangeMessageInfo desde el ExchangeMessageInfoCollection devuelto por ListMessages(). El otro argumento es el MailMessage con el texto y los archivos adjuntos de la respuesta. Para realizar esta tarea:

  1. Inicialice el IEWSClient objeto proporcionando credenciales válidas.
  2. Encuentre el mensaje al que responder.
  3. Llame al Reply(), ReplyAll() y Forward() métodos para enviar las respuestas.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://exchange.domain.com/ews/Exchange.asmx", u"username", u"password");

try
{
    // a message to respond to
    client->Send(MakeObject<MailMessage>(u"user@domain.com", u"user@domain.com", u"TestMailRefw", u"The original message"));
    SharedPtr<ExchangeMessageInfoCollection> messages = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());

    // the text and the attachments of the response
    SharedPtr<MailMessage> response = MakeObject<MailMessage>(u"user@domain.com", u"user@domain.com", u"TestMailRefw", u"The response");
    response->get_Attachments()->Add(Attachment::CreateAttachmentFromString(u"Test attachment 1", u"Attachment Name 1"));
    response->get_Attachments()->Add(Attachment::CreateAttachmentFromString(u"Test attachment 2", u"Attachment Name 2"));

    client->Reply(response, messages->idx_get(0));
    client->ReplyAll(response, messages->idx_get(0));
    client->Forward(response, messages->idx_get(0));
}
catch (System::Exception& ex)
{
    Console::WriteLine(u"Error in program: " + ex->get_Message());
}

client->Dispose();

Agregar encabezados en solicitudes EWS

Los encabezados HTTP personalizados pueden añadirse a cada solicitud EWS que el cliente envía. Un caso común es X-AnchorMailbox, que enruta las solicitudes de una aplicación al servidor que aloja el buzón y ayuda contra la limitación de cuota en Exchange Online. El AddHeader método de IEWSClient añade tal encabezado.

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

client->AddHeader(u"X-AnchorMailbox", u"username@domain.com");
SharedPtr<ExchangeMessageInfoCollection> messages = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
Console::WriteLine(u"Messages: " + Convert::ToString(messages->get_Count()));

client->Dispose();

Trabajando con mensajería unificada

Exchange Server 2010 y posteriores combinan el correo de voz y el correo electrónico en un mismo buzón: mensajería unificada. GetUMConfiguration devuelve el UnifiedMessagingConfiguration del buzón: si la mensajería unificada está habilitada y el número usado para reproducir mensajes en un teléfono. El cliente también puede iniciar una llamada saliente, leer la información de una llamada por su ID y desconectarla.

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

SharedPtr<UnifiedMessagingConfiguration> configuration = client->GetUMConfiguration();
Console::WriteLine(u"Unified messaging enabled: " + Convert::ToString(configuration->get_UMEnabled()));
Console::WriteLine(u"Play on phone: " + Convert::ToString(configuration->get_PlayOnPhoneEnabled()) +
    u", dial string: " + configuration->get_PlayOnPhoneDialString());

client->Dispose();

Obteniendo consejos de correo

Exchange Server 2010 y posteriores pueden proporcionar consejos de correo mientras se redacta un mensaje: información sobre los destinatarios antes de enviar el mensaje. Un consejo informa, por ejemplo, que una dirección de destinatario es inválida o que un destinatario ha configurado una respuesta fuera de la oficina. Se requiere Exchange Server 2010 Service Pack 1 o posterior.

GetMailTipsOptions nombra al remitente, los destinatarios y los tipos de consejos a solicitar (MailTipsType); GetMailTips devuelve uno MailTips objeto por destinatario. El segundo argumento del MailAddress constructores a continuación, true, omite la verificación sintáctica de las direcciones.

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

SharedPtr<MailAddressCollection> recipients = MakeObject<MailAddressCollection>();
recipients->Add(MakeObject<MailAddress>(u"test.exchange@ex2010.local", true));
recipients->Add(MakeObject<MailAddress>(u"invalid.recipient@ex2010.local", true));

SharedPtr<GetMailTipsOptions> options = MakeObject<GetMailTipsOptions>(
    MakeObject<MailAddress>(u"administrator@ex2010.local", true), recipients, MailTipsType::All);

try
{
    for (SharedPtr<MailTips> tip : client->GetMailTips(options))
    {
        if (tip->get_OutOfOffice() != nullptr)
        {
            Console::WriteLine(u"Out of office: " + tip->get_OutOfOffice()->get_ReplyBody()->get_Message());
        }

        if (tip->get_InvalidRecipient())
        {
            Console::WriteLine(u"The recipient address is invalid: " + tip->get_RecipientAddress()->get_Address());
        }
    }
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();