C# で IMAP 接続を確立する方法
IMAP サーバー拡張機能の一覧表示
Aspose.Email の ImapClient サーバーがサポートする IDLE、UNSELECT、QUOTA などの拡張機能を取得できるようにします。これにより、特定の機能をクライアントで使用する前に拡張機能の有無を確認できます。 GetCapabilities() メソッドは、サポートされている拡張タイプを文字列配列で返します。以下のコードスニペットは、拡張機能を取得する方法を示しています。
標準 IMAP 接続
この ImapClient クラスは、アプリケーションが IMAP プロトコルを使用して IMAP メールボックスを管理できるようにします。 ImapClient クラスは IMAP メールサーバーに接続し、IMAP フォルダー内のメールを管理するために使用されます。IMAP サーバーに接続するには
- インスタンスを作成します ImapClient クラス。
- ホスト名、ユーザー名、パスワードを以下で指定します。 ImapClient コンストラクタ.
※ パスワード制限はサーバーの要件を満たす必要があります。メールクライアントはパスワード制限を追加しません。
一度 ImapClient インスタンスが初期化されると、このインスタンスを使用した次の操作呼び出しでサーバーに接続します。以下のコードスニペットは、上記の手順を使用して IMAP サーバーに接続する方法を示します。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an imapclient with host, user and password
ImapClient client = new ImapClient("localhost", "user", "password");
SSL 対応 IMAP 接続
IMAP サーバーへの接続 IMAP サーバーへの接続方法を4つの簡単な手順で説明します:
- インスタンスを作成します ImapClient クラス。
- ホスト名、ユーザー名、パスワードを指定します。
- ポートを指定します。
- セキュリティオプションを指定します。
SSL が有効な IMAP サーバーへの接続手順は似ていますが、いくつかの追加プロパティを設定する必要があります:
- 設定 SecurityOptions SSLImplicit に。
以下のコードスニペットは、方法を示します。
- ユーザー名、パスワード、ポートを設定します。
- セキュリティオプションを設定します。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an instance of the ImapClient class
ImapClient client = new ImapClient("imap.domain.com", 993, "user@domain.com", "pwd");
// Set the security mode to implicit
client.SecurityOptions = SecurityOptions.SSLImplicit;
プロキシ接続の設定
プロキシ経由でサーバーに接続
プロキシサーバーは外部と通信する際によく使用されます。このような場合、メールクライアントはプロキシアドレスを指定しないとインターネットに接続できません。Aspose.Email は SOCKS プロトコルのバージョン 4、4a、5 をサポートしています。本記事では、プロキシメールサーバーを使用してメールボックスにアクセスする動作サンプルを提供します。プロキシサーバー経由でメールボックスにアクセスするには:
- 初期化 Socksプロキシ 必要な情報(プロキシアドレス、ポート、SOCKS バージョン)と共に。
- 初期化 ImapClient ホストアドレス、ユーザー名、パスワード、その他の設定と共に。
- クライアントの設定を Socksプロキシ クライアントのプロパティを Socksプロキシ 上記で作成したオブジェクト。
以下のコードスニペットは、プロキシサーバー経由でメールボックスを取得する方法を示します。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Connect and log in to IMAP and set SecurityOptions
ImapClient client = new ImapClient("imap.domain.com", "username", "password");
client.SecurityOptions = SecurityOptions.Auto;
string proxyAddress = "192.168.203.142"; // proxy address
int proxyPort = 1080; // proxy port
SocksProxy proxy = new SocksProxy(proxyAddress, proxyPort, SocksVersion.SocksV5);
// Set the proxy
client.Proxy = proxy;
try
{
client.SelectFolder("Inbox");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
HTTP プロキシ経由でサーバーに接続
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
HttpProxy proxy = new HttpProxy("18.222.124.59", 8080);
using (ImapClient client = new ImapClient("imap.domain.com", "username", "password"))
{
client.Proxy = proxy;
client.SelectFolder("Inbox");
}
読み取り専用モード接続
この ImapClient クラスは以下を提供します。 ReadOnly true に設定された場合、メールボックスの永続状態に変更を加えないことを示すプロパティです。以下のコードサンプルは、の使用例を示します。 ImapClient.ReadOnly プロパティです。未読メッセージ数を取得し、1 通のメッセージを取得し、読み取り専用モードで再び未読メッセージ数を取得します。未読メッセージ数が変わらないことは、メールボックスの永続状態が変更されていないことを示します。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
ImapClient imapClient = new ImapClient();
imapClient.Host = "<HOST>";
imapClient.Port = 993;
imapClient.Username = "<USERNAME>";
imapClient.Password = "<PASSWORD>";
imapClient.SupportedEncryption = EncryptionProtocols.Tls;
imapClient.SecurityOptions = SecurityOptions.SSLImplicit;
ImapQueryBuilder imapQueryBuilder = new ImapQueryBuilder();
imapQueryBuilder.HasNoFlags(ImapMessageFlags.IsRead); /* get unread messages. */
MailQuery query = imapQueryBuilder.GetQuery();
imapClient.ReadOnly = true;
imapClient.SelectFolder("Inbox");
ImapMessageInfoCollection messageInfoCol = imapClient.ListMessages(query);
Console.WriteLine("Initial Unread Count: " + messageInfoCol.Count());
if (messageInfoCol.Count() > 0)
{
imapClient.FetchMessage(messageInfoCol[0].SequenceNumber);
messageInfoCol = imapClient.ListMessages(query);
// This count will be equal to the initial count
Console.WriteLine("Updated Unread Count: " + messageInfoCol.Count());
}
else
{
Console.WriteLine("No unread messages found");
}
CRAM-MD5 認証の設定
安全な認証とメールサーバーへのアクセスのために、Aspose.Email for .NET は CRAM-MD5 認証方式を提供しています。以下のコードスニペットは、ImapClient での使用方法を示しています。
imapClient.AllowedAuthentication = ImapKnownAuthenticationType.CramMD5;
IMAP 操作のタイムアウト設定
メール操作は、ネットワーク遅延、データサイズ、サーバー性能など多数の要因により時間がかかります。すべてのメール操作にタイムアウトを設定できます。以下のコード例は、次のものを使用してその方法を示しています。 タイムアウト プロパティ。注意:アプリケーションで長時間待たされるのを防ぐために大きな値は設定しないでください。
操作タイムアウトの設定
using (ImapClient imapClient = new ImapClient("host", 993, "username", "password", SecurityOptions.SSLImplicit))
{
imapClient.Timeout = 60000; // 60 seconds
// some code...
}
Greeting タイムアウトの制限
IMAP クライアントは自動モードで接続を確立できる場合があります。このモードでは、接続が確立するまで可能なすべての接続パラメータを順に試みます。正しく接続できた場合、IMAP サーバーはクライアントに挨拶文字列を送信します。サーバーは暗黙的(implicit)または明示的(START TLS)な SSL/TLS 接続の開始を使用することがあります。接続モードが一致しない場合(例: サーバーが暗黙的 SSL 接続を待っているのに、クライアントが非保護または明示的 SSL 接続を試みる)では、サーバーは挨拶文字列を送らず、タイムアウトが発生するまで長時間待機することになります。その結果、クライアントは次の接続オプションへ進みます。この問題を回避するために、GreetingTimeout プロパティが導入されました。このプロパティにより、挨拶文字列のタイムアウトを設定でき、自動接続確立にかかる時間を短縮できます。
using (ImapClient client = new ImapClient("localhost", 993, "username", "password"))
{
client.GreetingTimeout = 4000;
client.SelectFolder(ImapFolderInfo.InBox);
}
IMAP で暗号化プロトコルを使用する
Aspose.Email は、通信セキュリティを提供するために SSL(旧式)および TLS 暗号プロトコルをサポートしています。アプリケーションとメールサーバー間のデータ交換を保護するために暗号化を有効にできます。
注意: .NET Framework がサポートするプロトコルのバージョンのみを設定してください。現在の .NET Framework でサポートされていない暗号プロトコルのバージョンは無視され、スキップされます。この場合、例外は生成されません。以下を使用してください SetSupportedEncryptionUnsafe 互換性チェックなしでプロトコルを設定したい場合のメソッドです。
以下のコード例は、TLS 1.3 を設定する方法を示しています。 ImapClient クラスのインスタンスです。
using (ImapClient imapClient = new ImapClient("host", 993, "username", "password", SecurityOptions.SSLImplicit))
{
imapClient.SupportedEncryption = EncryptionProtocols.Tls13;
// some code...
}
指定された暗号化プロトコルが現在の .NET Framework バージョンでサポートされていない場合、次の間で動作の違いがあります SetSupportedEncryptionUnsafe メソッドと SupportedEncryption プロパティは次のとおりです:
- もし SupportedEncryption このプロパティが使用されると、メールクライアントは暗号化プロトコルをサポートされたレベルにダウングレードします。
- もし SetSupportedEncryptionUnsafe このメソッドが使用されると、メールクライアントは例外をスローします。
IMAP IDLE コマンドの使用
Aspose.Email API ImapClient サーバーへの接続を開き、メールメッセージの到着を待機する機能を提供します。これにより、受信メールのたびにサーバーをポーリングする必要がなくなります。以下のコードスニペットは、Aspose.Email ライブラリを使用して IMAP メール受信箱を新規メッセージおよび削除メッセージについて監視し、これらのイベントに基づいて特定のアクションを実行する方法を示しています。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Connect and log in to IMAP
ImapClient client = new ImapClient("imap.domain.com", "username", "password");
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
ImapMonitoringEventArgs eventArgs = null;
client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e)
{
eventArgs = e;
manualResetEvent.Set();
});
Thread.Sleep(2000);
SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password");
smtpClient.Send(new MailMessage("from@aspose.com", "to@aspose.com", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
manualResetEvent.WaitOne(10000);
manualResetEvent.Reset();
Console.WriteLine(eventArgs.NewMessages.Length);
Console.WriteLine(eventArgs.DeletedMessages.Length);
client.StopMonitoring("Inbox");
smtpClient.Send(new MailMessage("from@aspose.com", "to@aspose.com", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
manualResetEvent.WaitOne(5000);
以下のコードサンプルは、新しいメールメッセージを 非同期 に監視する設定方法を示しています。
var client = = new ImapClient("imap.domain.com", "username", "password");
//anySuccess is a flag to prevent infinite Client.ResumeMonitoring calls
var anySuccess = false;
await client.StartMonitoringAsync(OnNewMessagesCallback, OnErrorCallback);
void OnErrorCallback(object eventSender, ImapMonitoringErrorEventArgs errorEventArguments)
{
//The exception can be handled here
Logger.Debug.Write(
$"An error occured while folder monitoring: {errorEventArguments.FolderName}",
errorEventArguments.Error);
//IMAP folder monitoring is stopped on any error. Here is an example
//of resuming after that.
if (!anySuccess) return;
anySuccess = false;
//Make sure you use ResumeMonitoring instead of StartMonitoring here
//to prevent missing any emails between the error handling and resuming.
client.ResumeMonitoring(OnNewMessagesCallback, OnErrorCallback,
errorEventArguments.MonitoringState);
}
void OnNewMessagesCallback(object sender, ImapMonitoringEventArgs successEventArgs)
{
anySuccess = true;
//Use successEventArgs.NewMessages to handle new messages
//Use successEventArgs.DeletedMessages to handle deleted messages
}
IMAP 拡張のサポート
Aspose.Email API は IMAP 拡張のサポートを提供します。現在、API がサポートしている IMAP 拡張は以下の通りです。これらの拡張はすべてのサーバーでサポートされているわけではありません。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (ImapClient client = new ImapClient("imap.gmail.com", 993, "username", "password"))
{
// Set SecurityOptions
client.SecurityOptions = SecurityOptions.Auto;
Console.WriteLine(client.IdSupported.ToString());
ImapIdentificationInfo serverIdentificationInfo1 = client.IntroduceClient();
ImapIdentificationInfo serverIdentificationInfo2 = client.IntroduceClient(ImapIdentificationInfo.DefaultValue);
// Display ImapIdentificationInfo properties
Console.WriteLine(serverIdentificationInfo1.ToString(), serverIdentificationInfo2);
Console.WriteLine(serverIdentificationInfo1.Name);
Console.WriteLine(serverIdentificationInfo1.Vendor);
Console.WriteLine(serverIdentificationInfo1.SupportUrl);
Console.WriteLine(serverIdentificationInfo1.Version);
}
IMAP4 拡張リストコマンド
以下のコードスニペットは、IMAP4 拡張リストコマンドの使用方法を示します。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (ImapClient client = new ImapClient("imap.gmail.com", 993, "username", "password"))
{
ImapFolderInfoCollection folderInfoCol = client.ListFolders("*");
Console.WriteLine("Extended List Supported: " + client.ExtendedListSupported);
foreach (ImapFolderInfo folderInfo in folderInfoCol)
{
switch (folderInfo.Name)
{
case "[Gmail]/All Mail":
Console.WriteLine("Has Children: " + folderInfo.HasChildren);
break;
case "[Gmail]/Bin":
Console.WriteLine("Bin has children? " + folderInfo.HasChildren);
break;
case "[Gmail]/Drafts":
Console.WriteLine("Drafts has children? " + folderInfo.HasChildren);
break;
case "[Gmail]/Important":
Console.WriteLine("Important has Children? " + folderInfo.HasChildren);
break;
case "[Gmail]/Sent Mail":
Console.WriteLine("Sent Mail has Children? " + folderInfo.HasChildren);
break;
case "[Gmail]/Spam":
Console.WriteLine("Spam has Children? " + folderInfo.HasChildren);
break;
case "[Gmail]/Starred":
Console.WriteLine("Starred has Children? " + folderInfo.HasChildren);
break;
}
}
}