C#에서 IMAP 연결을 설정하는 방법
IMAP 서버 확장 기능 나열
Aspose.Email의 ImapClient 서버가 지원하는 IDLE, UNSELECT, QUOTA 등과 같은 확장 기능을 검색할 수 있게 해줍니다. 이를 통해 특정 기능을 사용하기 전에 해당 확장 기능의 가용성을 확인할 수 있습니다. GetCapabilities() 메서드는 지원되는 확장 유형을 문자열 배열 형태로 반환합니다. 다음 코드 스니펫은 확장을 검색하는 방법을 보여줍니다.
표준 IMAP 연결
다음은 ImapClient 클래스는 애플리케이션이 IMAP 프로토콜을 사용하여 IMAP 메일함을 관리하도록 허용합니다. ImapClient 클래스는 IMAP 메일 서버에 연결하고 IMAP 이메일 폴더에서 이메일을 관리하는 데 사용됩니다. IMAP 서버에 연결하려면
- 다음의 인스턴스를 생성합니다. ImapClient 클래스.
- 호스트 이름, 사용자 이름 및 비밀번호를 지정합니다 ImapClient constructor.
참고: 비밀번호 제한은 서버 요구 사항을 충족해야 합니다. 이메일 클라이언트는 비밀번호 제한을 추가하지 않습니다.
일단 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 서버에 연결하는 네 단계에 대해 설명했습니다:
- 다음의 인스턴스를 생성합니다. 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를 지원합니다. 이 문서는 프록시 메일 서버를 사용하여 메일함에 접근하는 작동 예제를 제공합니다. 프록시 서버를 통해 메일함에 접근하려면:
- 초기화 SocksProxy 필수 정보인 프록시 주소, 포트 및 SOCKS 버전을 지정합니다.
- 초기화 ImapClient 호스트 주소, 사용자 이름, 비밀번호 및 기타 설정과 함께.
- 클라이언트 설정 SocksProxy 클라이언트의 속성 SocksProxy 위에서 생성된 객체.
다음 코드 스니펫은 프록시 서버를 통해 메일함을 검색하는 방법을 보여줍니다.
// 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 속성입니다. 읽지 않은 메시지 수를 가져온 다음 하나의 메시지를 가져오고, 읽기 전용 모드에서 다시 읽지 않은 메시지 수를 가져옵니다. 읽지 않은 메시지 수가 동일하게 유지되어 메일함의 영구 상태가 변경되지 않았음을 나타냅니다.
// 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...
}
환영 타임아웃 제한
IMAP 클라이언트는 자동 모드를 사용하여 연결을 설정할 수 있습니다. 이 모드에서는 연결이 확립될 때까지 가능한 모든 연결 매개변수를 시도합니다. 올바른 연결인 경우 IMAP 서버는 클라이언트에 환영 문자열을 보냅니다. 서버는 암시적 또는 명시적 (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 암호화 프로토콜을 지원하여 통신 보안을 제공합니다. 애플리케이션과 메일 서버 간 데이터 교환을 보호하려면 암호화 암호화를 활성화할 수 있습니다.
NOTE: .NET Framework에서 지원하는 프로토콜 버전만 설정해야 합니다. 현재 사용 중인 .NET Framework 버전에서 지원되지 않는 암호화 프로토콜 버전은 무시되고 건너뛰어집니다. 이 경우 예외가 발생하지 않습니다. Please use 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 속성은 다음과 같습니다:
- If SupportedEncryption 이 속성이 사용되면 이메일 클라이언트가 암호화 프로토콜을 지원되는 수준으로 낮춥니다.
- If 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 확장은 다음과 같습니다. 이러한 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;
}
}
}