Connessione a Exchange Server

Per connettersi ai server Exchange 2007, 2010 e 2013 usando Exchange Web Service, Aspose.Email fornisce il IEWSClient interfaccia che implementa il EWSClient classe. Il EWSClient.getEWSClient il metodo istanzia e restituisce un IEWSClient oggetto che è poi usato per eseguire operazioni relative a una casella di posta Exchange e altre cartelle. Questo articolo mostra come istanziare oggetti di IEWSClient.

Connessione a Exchange Server usando EWS

Il seguente frammento di codice mostra come connettersi usando Exchange Web Service (EWS).

private static IEWSClient getExchangeEWSClient() {
    final String mailboxUri = "https://outlook.office365.com/ews/exchange.asmx";
    final String domain = "";
    final String username = "username@onmicrosoft.com";
    final String password = "password";
    NetworkCredential credentials = new NetworkCredential(username, password, domain);
    IEWSClient client = EWSClient.getEWSClient(mailboxUri, credentials);
    return client;
}

Connessione a Exchange Server usando IMAP

Microsoft Exchange Server supporta il protocollo IMAP per accedere agli elementi di una casella di posta. Usa le funzionalità di Aspose.Email ImapClient classe per connettersi a Exchange Server usando il protocollo IMAP. Per ulteriori informazioni su ImapClient classe. Prima, assicurati che i servizi IMAP siano abilitati per il tuo Exchange Server:

  1. Apri il Pannello di controllo.
  2. Vai su Strumenti di amministrazione, poi Servizi.
  3. Verifica lo stato del servizio Microsoft Exchange IMAP4.
  4. Se non è già in esecuzione, abilitalo/avvialo.

Il seguente frammento di codice mostra come connettersi e elencare i messaggi dalla cartella Posta in arrivo del server Microsoft Exchange usando il protocollo IMAP.

// Connect to Exchange Server using ImapClient class
ImapClient imapClient = new ImapClient("ex07sp1", "Administrator", "Evaluation1");
imapClient.setSecurityOptions(SecurityOptions.Auto);

// Select the Inbox folder
imapClient.selectFolder(ImapFolderInfo.IN_BOX);

// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.listMessages();
for (ImapMessageInfo msgInfo : (Iterable<ImapMessageInfo>) msgCollection) {
    System.out.println(msgInfo.getSubject());
}
// Disconnect from the server
imapClient.dispose();

Il seguente frammento di codice mostra come usare SSL.

public static void run() {
    // Connect to Exchange Server using ImapClient class
    ImapClient imapClient = new ImapClient("ex07sp1", 993, "Administrator", "Evaluation1");
    imapClient.setSecurityOptions(SecurityOptions.SSLExplicit);

    // Select the Inbox folder
    imapClient.selectFolder(ImapFolderInfo.IN_BOX);

    // Get the list of messages
    ImapMessageInfoCollection msgCollection = imapClient.listMessages();
    for (ImapMessageInfo msgInfo : (Iterable<ImapMessageInfo>) msgCollection) {
        System.out.println(msgInfo.getSubject());
    }
    // Disconnect from the server
    imapClient.dispose();
}

Dopo essersi connessi a un server Exchange usando IMAP e avere ottenuto il IMapMessageInfoCollection, Il seguente frammento di codice mostra come usare il MessageInfo numero di sequenza dell’oggetto per salvare un messaggio specifico.

// Select the Inbox folder
imapClient.selectFolder(ImapFolderInfo.IN_BOX);
// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.listMessages();
for (ImapMessageInfo msgInfo : (Iterable<ImapMessageInfo>) msgCollection) {
    // Fetch the message from inbox using its SequenceNumber from msgInfo
    MailMessage message = imapClient.fetchMessage(msgInfo.getSequenceNumber());

    // Save the message to disc now
    message.save(dataDir + msgInfo.getSequenceNumber() + "_out.msg", SaveOptions.getDefaultMsgUnicode());
}

Ignora o Bypassa Certificato SSL Non Valido o Scaduto

Aspose.Email si connette a Exchange Server via HTTPS, quindi la JVM valida il certificato del server prima di qualsiasi richiesta EWS. Se il certificato è scaduto, autofirmato o il suo soggetto non corrisponde al nome host, la connessione fallisce con un SSLHandshakeException.

La correzione supportata è installare il certificato del server (o la CA che lo ha emesso) nel trust store della JVM:

keytool -importcert -alias exchange -file exchange.cer -keystore "%JAVA_HOME%\lib\security\cacerts"

Per un ambiente di test o sviluppo in cui ciò non è pratico, puoi registrare un TrustManager e il verificatore del nome host prima di creare il client. Chiama questo metodo una volta all’avvio dell’applicazione:

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

public class SslBypass {

  public static void trustAllCertificates() throws Exception {
      TrustManager[] trustAll = new TrustManager[] {
          new X509TrustManager() {
              public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
              public void checkClientTrusted(X509Certificate[] chain, String authType) { }
              public void checkServerTrusted(X509Certificate[] chain, String authType) { }
          }
      };

      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, trustAll, new java.security.SecureRandom());

      HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
  }
}