Funciones utilitarias en Aspose.Email para .NET

Trabajando con mensajería unificada

Aspose.Email puede recuperar información de mensajería unificada del Exchange Server 2010. Mensajería unificada como obtener información de configuración, iniciar una llamada saliente, recuperar información de llamadas telefónicas por ID de llamada y desconectar una llamada telefónica por ID está soportada actualmente. El siguiente ejemplo de código muestra cómo recuperar la información de configuración de mensajería unificada del Microsoft Exchange Server 2010.

IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credential);
UnifiedMessagingConfiguration umConf = client.GetUMConfiguration();

Obteniendo consejos de correo

Microsoft Exchange Server añadió varias funciones nuevas con Exchange Server 2010 y 2013. Una de ellas permite a los usuarios obtener sugerencias de correo al redactar un mensaje de correo electrónico. Estas sugerencias son muy útiles ya que proporcionan información antes de que se envíe el correo. Por ejemplo, si una dirección de correo es incorrecta en la lista de destinatarios, se muestra una sugerencia para indicar que la dirección no es válida. Las sugerencias de correo también le permiten ver respuestas fuera de la oficina antes de enviar un correo: Exchange Server (2010 y 2013) envía la sugerencia mientras se redacta el correo si uno o más de los destinatarios han configurado respuestas fuera de la oficina. Se requiere Microsoft Exchange Server 2010 Service Pack 1 para todas las funciones demostradas en este artículo. El siguiente fragmento de código le muestra cómo usar el EWSClient clase que usa Exchange Web Services, disponible en Microsoft Exchange Server 2007 y versiones posteriores.

// Create instance of EWSClient class by giving credentials
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
Console.WriteLine("Connected to Exchange server...");
// Provide mail tips options
MailAddressCollection addrColl = new MailAddressCollection();
addrColl.Add(new MailAddress("test.exchange@ex2010.local", true));
addrColl.Add(new MailAddress("invalid.recipient@ex2010.local", true));
GetMailTipsOptions options = new GetMailTipsOptions("administrator@ex2010.local", addrColl, MailTipsType.All);

// Get Mail Tips
MailTips[] tips = client.GetMailTips(options);

// Display information about each Mail Tip
foreach (MailTips tip in tips)
{
    // Display Out of office message, if present
    if (tip.OutOfOffice != null)
    {
        Console.WriteLine("Out of office: " + tip.OutOfOffice.ReplyBody.Message);
    }

    // Display the invalid email address in recipient, if present
    if (tip.InvalidRecipient == true)
    {
        Console.WriteLine("The recipient address is invalid: " + tip.RecipientAddress);
    }
}

Suplantación en Exchange

La suplantación en Exchange permite a alguien suplantar otra cuenta y realizar tareas y operaciones usando los permisos de la cuenta suplantada en lugar de los propios. Mientras que la delegación permite a los usuarios actuar en nombre de otros usuarios, la suplantación les permite actuar como otros usuarios. Aspose.Email admite la suplantación en Exchange. El EWSClient class proporciona el ImpersonateUser y ResetImpersonation métodos para facilitar esta función.

Para realizar esta tarea:

  1. Inicializar el ExchangeWebServiceClient para el usuario 1.
  2. Inicializar el ExchangeWebServiceClient para el usuario 2.
  3. Agregar mensajes de prueba a las cuentas.
  4. Habilitar suplantación.
  5. Restablecer suplantación.

El siguiente fragmento de código muestra cómo usar el EWSClient clase para implementar la función de suplantación.

// Create instance's of EWSClient class by giving credentials
IEWSClient client1 = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser1", "pwd", "domain");
IEWSClient client2 = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser2", "pwd", "domain");
{
    string folder = "Drafts";
    try
    {
        foreach (ExchangeMessageInfo messageInfo in client1.ListMessages(folder))
            client1.DeleteItem(messageInfo.UniqueUri, DeletionOptions.DeletePermanently);
        string subj1 = string.Format("NETWORKNET_33354 {0} {1}", "User", "User1");
        client1.AppendMessage(folder, new MailMessage("User1@exchange.conholdate.local", "To@aspsoe.com", subj1, ""));

        foreach (ExchangeMessageInfo messageInfo in client2.ListMessages(folder))
            client2.DeleteItem(messageInfo.UniqueUri, DeletionOptions.DeletePermanently);
        string subj2 = string.Format("NETWORKNET_33354 {0} {1}", "User", "User2");
        client2.AppendMessage(folder, new MailMessage("User2@exchange.conholdate.local", "To@aspose.com", subj2, ""));

        ExchangeMessageInfoCollection messInfoColl = client1.ListMessages(folder);
        //Assert.AreEqual(1, messInfoColl.Count);
        //Assert.AreEqual(subj1, messInfoColl[0].Subject);

        client1.ImpersonateUser(ItemChoice.PrimarySmtpAddress, "User2@exchange.conholdate.local");
        ExchangeMessageInfoCollection messInfoColl1 = client1.ListMessages(folder);
        //Assert.AreEqual(1, messInfoColl1.Count);
        //Assert.AreEqual(subj2, messInfoColl1[0].Subject);

        client1.ResetImpersonation();
        ExchangeMessageInfoCollection messInfoColl2 = client1.ListMessages(folder);
        //Assert.AreEqual(1, messInfoColl2.Count);
        //Assert.AreEqual(subj1, messInfoColl2[0].Subject);
    }
    finally
    {
        try
        {
            foreach (ExchangeMessageInfo messageInfo in client1.ListMessages(folder))
                client1.DeleteItem(messageInfo.UniqueUri, DeletionOptions.DeletePermanently);
            foreach (ExchangeMessageInfo messageInfo in client2.ListMessages(folder))
                client2.DeleteItem(messageInfo.UniqueUri, DeletionOptions.DeletePermanently);
        }
        catch { }
    }
}

Funcionalidad Auto Discover usando EWS

La API Aspose.Email le permite descubrir la configuración del servidor Exchange usando el cliente EWS. 

string email = "asposeemail.test3@aspose.com";
string password = "Aspose@2017";
AutodiscoverService svc = new AutodiscoverService();
svc.Credentials = new NetworkCredential(email, password);

IDictionary<UserSettingName, object> userSettings = svc.GetUserSettings(email, UserSettingName.ExternalEwsUrl).Settings;
string ewsUrl = (string)userSettings[UserSettingName.ExternalEwsUrl];
Console.WriteLine("Auto discovered EWS Url: "  + ewsUrl);

Abortar restauración de PST a Exchange Server

La API Aspose.Email le permite restaurar un archivo PST en Exchange Server. Sin embargo, si la operación lleva mucho tiempo debido al gran tamaño del archivo PST, puede ser necesario especificar un criterio para abortar la operación. Esto se puede lograr usando la API como se muestra en el siguiente código de ejemplo.

Nota: El ejemplo también necesita que se agregue la siguiente clase.


 public class CustomAbortRestoreException : Exception { }
using (IEWSClient client = EWSClient.GetEWSClient("https://exchange.office365.com/ews/exchange.asmx", "username", "password"))
{
    DateTime startTime = DateTime.Now;
    TimeSpan maxRestoreTime = TimeSpan.FromSeconds(15);
    int processedItems = 0;

    BeforeItemCallback callback = delegate
    {
        if (DateTime.Now >= startTime.Add(maxRestoreTime))
        {
            throw new CustomAbortRestoreException();
        }

        processedItems++;
    };

    try
    {
        //create a test pst and add some test messages to it
        var pst = PersonalStorage.Create(new MemoryStream(), FileFormatVersion.Unicode);
        var folder = pst.RootFolder.AddSubFolder("My test folder");
        for (int i = 0; i < 20; i++)
        {
            var message = new MapiMessage("from@gmail.com", "to@gmail.com", "subj", new string('a', 10000));
            folder.AddMessage(message);
        }

        //now restore the PST with callback
        client.Restore(pst, new Aspose.Email.Clients.Exchange.WebService.RestoreSettings
        {
            BeforeItemCallback = callback
        });
        Console.WriteLine("Success!");
    }
    catch (CustomAbortRestoreException)
    {
        Console.WriteLine($"Timeout! {processedItems}");
    }