EWS と IMAP を使用して Exchange Server に接続する

Exchange Web Service を使用して Exchange Server 2007、2010、2013 に接続するために、Aspose.Email は IEWSClient インターフェースは次の機能を実装します。 EWSClient クラス。 EWSClient.GetEWSClient メソッドはインスタンス化して返します。 IEWSClient このオブジェクトは、Exchange メールボックスや他のフォルダーに関連する操作を実行するために使用されます。本記事では、以下のオブジェクトのインスタンス化方法を示します。 IEWSClient.

EWS を使用した Exchange Server への接続

以下のコードスニペットは、Exchange Web Service (EWS) を使用して接続を確立する方法を示しています。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
private static IEWSClient GetExchangeEWSClient()
{
    const string mailboxUri = "https://outlook.office365.com/ews/exchange.asmx";
    const string domain = @"";
    const string username = @"username@ASE305.onmicrosoft.com";
    const string password = @"password";
    NetworkCredential credentials = new NetworkCredential(username, password, domain);
    IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credentials);
    return client;
}

EWSClient 初期化時にカスタムヘッダーを追加する

クライアント初期化時に特定のヘッダー(例: EWS の X-AnchorMailbox ヘッダー)が必要なシナリオでは、インスタンス作成時にカスタムヘッダーを追加するために、以下のオーバーロード メソッドを使用してください。 IEWSClient:

  • IEWSClient GetEWSClient(string mailboxUri, ICredentials credentials, WebProxy proxy, Dictionary headers)

  • async Task GetEwsClientAsync(string mailboxUri, ICredentials credentials, WebProxy proxy, CancellationToken cancellationToken , Dictionary headers)

以下のコードサンプルは、カスタム HTTP ヘッダーを利用して IEWSClient を構成および初期化する方法を示しています。

var headers = new Dictionary<string, string>();
headers.Add("X-AnchorMailbox", smtpExampleAddress);
IEWSClient client = EWSClient.GetEWSClient(HttpsExampleCom, new OAuthNetworkCredential("UserName", "Token"), null, headers);

IMAP を使用した Exchange Server への接続

Microsoft Exchange Server はメールボックス内のアイテムにアクセスするために IMAP プロトコルをサポートしています。Aspose.Email を使用してください。 ImapClient IMAP プロトコルを使用して Exchange Server に接続するクラスです。詳細については、 ImapClient クラスです。まず、Exchange Server で IMAP サービスが有効になっていることを確認してください:

  1. コントロール パネルを開きます。
  2. 管理ツールに移動し、次にサービスを開きます。
  3. Microsoft Exchange IMAP4 サービスのステータスを確認してください。
  4. まだ実行されていない場合は、有効に/開始してください。

次のコードスニペットは、IMAP プロトコルを使用して Microsoft Exchange Server の受信トレイフォルダーに接続し、メッセージを一覧表示する方法を示します。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Connect to Exchange Server using ImapClient class
ImapClient imapClient = new ImapClient("ex07sp1", "Administrator", "Evaluation1");
imapClient.SecurityOptions = SecurityOptions.Auto;

// Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox);

// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
foreach (ImapMessageInfo msgInfo in msgCollection)
{
    Console.WriteLine(msgInfo.Subject);
}
// Disconnect from the server
imapClient.Dispose();

次のコードスニペットは、SSL の使用方法を示します。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
public static void Run()
{            
    // Connect to Exchange Server using ImapClient class
    ImapClient imapClient = new ImapClient("ex07sp1", 993, "Administrator", "Evaluation1", new RemoteCertificateValidationCallback(RemoteCertificateValidationHandler));
    imapClient.SecurityOptions = SecurityOptions.SSLExplicit;

    // Select the Inbox folder
    imapClient.SelectFolder(ImapFolderInfo.InBox);

    // Get the list of messages
    ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
    foreach (ImapMessageInfo msgInfo in msgCollection)
    {
        Console.WriteLine(msgInfo.Subject);
    }
    // Disconnect from the server
    imapClient.Dispose();   
}

// Certificate verification handler
private static bool RemoteCertificateValidationHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true; // ignore the checks and go ahead
}

IMAP を使用して Exchange サーバーに接続し、取得した後、 IMapMessageInfoCollection、取得できます。 MessageInfo オブジェクトです。以下のコードスニペットは、シーケンス番号の使用方法を示します。 MessageInfo 特定のメッセージを保存するオブジェクトです。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox);
// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
foreach (ImapMessageInfo msgInfo in msgCollection)
{
    // Fetch the message from inbox using its SequenceNumber from msgInfo
    MailMessage message = imapClient.FetchMessage(msgInfo.SequenceNumber);

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

優先暗号化プロトコルの設定

EWS はサポートされる操作のために HTTPS 転送プロトコルを使用します。暗号化は SSL/TLS プロトコルによって提供されます。これらのプロトコルは .NET フレームワークで実装されており、現在のフレームワークのバージョンにより異なる場合があります。

SSL/TLS バージョンを設定するには、以下のコードを使用します。

var client = new ImapClient("some.host");
client.SupportedEncryption = EncryptionProtocols.Tls13;

または

var client = new ImapClient("some.host");
client.SetSupportedEncryptionUnsafe(EncryptionProtocols.Tls13);

注意: 指定された EncryptionProtocol が現在の .NET フレームワークのバージョンでサポートされていない場合、 SupportedEncryption プロパティは暗号化プロトコルをサポートされるレベルにダウングレードし、 SetSupportedEncryptionUnsafe メソッドは例外をスローします。

モダン認証で Exchange Server に接続する

このプロトコルは非推奨の Basic 認証よりも安全なため、モダン認証は新しい Microsoft 365/Azure テナントですべてデフォルトで有効になっています。

モダン認証は Active Directory Authentication Library と OAuth 2.0 に基づいています。期限付きトークンを使用し、アプリケーションはユーザー認証情報を保存しません。

前提条件設定

モダン認証を使用するには、必ず有効にしてください。ただし、2017 年 8 月 1 日以前に作成されたテナントは、デフォルトでモダン認証がオフになっています。 Microsoft 365 管理センターSettings > Org Settings > Modern Authentication に移動します。表示される Modern authentication フライアウトで、Basic 認証が不要になったプロトコルを確認できます。Azure の新しい Microsoft 365 テナントでは、すべてのアプリケーションで Basic 認証がデフォルトで無効になっています。そのため、テキストはこのセクションに表示されます。

組織でセキュリティ デフォルトが有効になっているため、Exchange Online へのモダン認証が必要で、Basic 認証接続はブロックされています。> ここで設定を変更する前に、Azure ポータルでセキュリティ デフォルトをオフにする必要があります。

テナントの Basic 認証サポートは、以下から有効にできます。 Azure ポータルで Azure Active Directory > Properties > Manage Security defaults > Enable Security defaults > No に進みます。詳細については、以下をご覧ください。 Microsoft ドキュメント記事.

Azure Active Directory でのアプリ登録

Azure Active Directory でアプリの登録を行う必要があります。アプリでメールボックスにアクセスするために使用できる権限は 2 種類あります。作成するアプリに応じて、特定の権限タイプを選択してください。

  • 委任権限 を使用するアプリはサインインしたユーザーが存在します。つまり、サービスに接続するとユーザー名とパスワードのダイアログが表示されます。アプリはサインインユーザー以上の権限を持つことはできません。
  • アプリケーション権限 を使用するアプリは、サインインしたユーザーがいなくても実行されます。例えば、バックグラウンドサービスやデーモンとして実行されるアプリです。アプリケーション権限への同意は管理者のみが行えます。

さらに、以下を参照してください。 Microsoft ドキュメント記事 詳しくは

登録手順は選択した権限のタイプに依存します。アプリを登録するには、以下を参照してください。 Microsoft ドキュメント記事.

EWSClient でモダン認証を使用する

アプリケーションを登録した後、コード作成に集中できます。コードは以下の部分で構成されます。

  • 認可トークンを取得します。
  • トークンを使用して認証します。

認可トークンの取得

トークンを取得するために使用します .NET 用 Microsoft Authentication Library (MSAL).

以下は認可トークンを取得する手順です。

  • 追加する Microsoft.Identity.Client NuGet パッケージ MSAL.NET のバイナリを含むものです。
  • 資格情報を保存する AccessParameters クラスを作成します。
  • アクセス パラメータを受け取り、MSAL.NET を使用してアクセストークンを取得するメソッドを作成します。

以下のコードサンプルは、選択した認証タイプに依存します。

委任認証でトークンを取得する

public class AccessParameters
{
    public string TenantId { get; set; }
    public string ClientId { get; set; }
    public string RedirectUri { get; set; } = "http://localhost";
    public string[] Scopes { get; set; } = { "https://outlook.office365.com/EWS.AccessAsUser.All" };
}

public static async Task<string> GetAccessToken(AccessParameters accessParameters)
{
    var pca = PublicClientApplicationBuilder
                            .Create(accessParameters.ClientId)
                            .WithTenantId(accessParameters.TenantId)
                            .WithRedirectUri(ccessParameters.RedirectUri)
                            .Build();

    var result = await pca.AcquireTokenInteractive(accessParameters.Scopes)
        .WithUseEmbeddedWebView(false)
        .ExecuteAsync();

    return result.AccessToken;
}

アプリ認証でトークンを取得する

public class AccessParameters
{
    public string TenantId { get; set; }
    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
    public string[] Scopes { get; set; } = { "https://outlook.office365.com/.default" };
}

public static async Task<string> GetAccessToken(AccessParameters accessParameters)
{
    var cca = ConfidentialClientApplicationBuilder
        .Create(accessParameters.ClientId)
        .WithClientSecret(accessParameters.ClientSecret)
        .WithTenantId(accessParameters.TenantId)
        .Build();

    var result = await cca.AcquireTokenForClient(accessParameters.Scopes).ExecuteAsync();

    return result.AccessToken;
}

トークンで認証する

その後、トークンを正常に取得したら、次のものを初期化しましょう。 EwsClient.

委任認証でトークンを使用する

NetworkCredential credentials = new OAuthNetworkCredential(accessToken);

using var client = EWSClient.GetEWSClient("https://outlook.office365.com/EWS/Exchange.asmx", credentials);

アプリ認証でトークンを使用する

// Use Microsoft365 username and access token
NetworkCredential credentials = new OAuthNetworkCredential(username, accessToken);

using var client = EWSClient.GetEWSClient("https://outlook.office365.com/EWS/Exchange.asmx", credentials);

IMAP、POP、SMTP クライアントでモダン認証を使用する

アプリケーション権限による IMAP、POP、SMTP アクセスはサポートされていません。つまり、委任認証のみがサポートされています。

Azure Active Directory でのアプリ登録手順は次のとおり定義されています 上記.

Microsoft 365 管理センターで IMAP、POP、SMTP AUTH を有効化または無効化する

  • 開く Microsoft 365 管理センター そして Users > Active users に移動します。
  • ユーザーを選択し、表示されるフライアウトで Mail をクリックします。
  • Email apps セクションで、Manage email apps をクリックします。
  • IMAP、POP、Authenticated SMTP 設定を確認してください: 未チェック = 無効、チェック = 有効。
  • Save changes をクリックしてください。

トークンサーバーから認証トークンを取得する

Outlook のリソース URL を含む完全なスコープを指定してください。

IMAP: https://outlook.office.com/IMAP.AccessAsUser.All POP: https://outlook.office.com/POP.AccessAsUser.All SMTP: https://outlook.office.com/SMTP.Send

トークンを取得するために使用します .NET 用 Microsoft Authentication Library (MSAL).

以下は認可トークンを取得する手順です。

  • 追加する Microsoft.Identity.Client NuGet パッケージ MSAL.NET のバイナリを含むものです。
  • 資格情報を保存する AccessParameters クラスを作成します。
  • アクセス パラメータを受け取り、MSAL.NET を使用してアクセストークンを取得するメソッドを作成します。
public class AccessParameters
{
    public string TenantId { get; set; }
    public string ClientId { get; set; }
    public string RedirectUri { get; set; } = "http://localhost";
    public string[] Scopes { get; set; } = { 
        "https://outlook.office.com/IMAP.AccessAsUser.All", 
        "https://outlook.office.com/SMTP.Send" };
}

public static async Task<string> GetAccessToken(AccessParameters accessParameters)
{
    var pca = PublicClientApplicationBuilder
                            .Create(accessParameters.ClientId)
                            .WithTenantId(accessParameters.TenantId)
                            .WithRedirectUri(ccessParameters.RedirectUri)
                            .Build();

    var result = await pca.AcquireTokenInteractive(accessParameters.Scopes)
        .WithUseEmbeddedWebView(false)
        .ExecuteAsync();

    return result.AccessToken;
}

トークンで認証する

その後、トークンを正常に取得したら、次のものを初期化しましょう。 ImapClient.

var imapClient = new ImapClient(
    "outlook.office365.com", 
    993, 
    username, 
    accessToken, 
    true);

同様に、 SmtpClient 初期化は次のようになります。

var smtpClient = new SmtpClient(
    "smtp.office365.com",
    587, 
    username,
    accessToken, 
    true);

クライアント要求 ID を返す

この ReturnClientRequestId EWSClient にプロパティが追加され、クライアント要求 ID を Exchange Web Services (EWS) 呼び出しの応答で返すかどうかを指定できるようになりました。クライアント要求 ID は、アプリケーションから送信する各 EWS リクエストに設定できる一意の識別子です。設定することにより、 ReturnClientRequestId プロパティを true に設定すると、EWS サーバーからの応答にクライアント要求 ID を含めるよう指定したことになります。これは、複数の要求が非同期に行われ処理されるシナリオで、要求と応答の追跡や相関付けに役立ちます。

以下のコードスニペットは、プロパティの使用方法を示しています。

using (IEWSClient client = TestUtil.CreateEWSClient(user))
{
   // Client will create random id and pass it to the server.
   // The server should include this id in request-id header of all responses.
   client.ReturnClientRequestId = true;
   
   client.LogFileName = "ews.log";
   client.GetMailboxInfo();
}

EWS リクエストに X-AnchorMailbox およびその他のヘッダーを追加する

Aspose.Email API は Exchange リクエストにヘッダーを追加することを可能にします。これは、さまざまな目的で使用できる異なるヘッダーを EWS リクエストに追加するために利用できます。例として、Exchange サーバーのスロットリング問題を管理するために使用される X-AnchorMailbox ヘッダーの追加があります。 AddHeader メソッド( IEWSClient 以下のコードスニペットに示すように、EWS リクエストにヘッダーを追加するために使用されます。

無効または期限切れの SSL 証明書を無視またはバイパスする

Aspose.Email は Exchange Server 上の SSL 証明書を両方の方法で処理できます。 ExchangeClient および EWSClient SSL 証明書が期限切れまたは無効になっている場合、Aspose.Email は無効な SSL 証明書が原因で例外をスローします。以下のコードで使用されている方法を使ってこれらの SSL 証明書エラーを無視することで回避できます。メインメソッドまたは init メソッドでコールバックハンドラを登録し、下記のメソッドをクラスのメンバーとして追加してください。