IMAP 서버에서 이메일 검색 및 목록화
메시지 검색 및 목록화
메일함 내 메시지 식별 정보 얻는 방법
이메일 메시지를 검색하고 처리할 때 최신 버전의 Aspose.Email for .NET이 제공하는 다음 기능을 이용하여 시퀀스 번호 및 고유 ID와 같은 상세 식별 정보를 얻을 수 있습니다:
Aspose.Email.ImapMessageInfo 클래스: IMAP 메일함 내 메시지에 대한 식별 정보를 나타냅니다.
ImapMessageInfo.SequenceNumber 속성: 메시지의 시퀀스 번호를 가져옵니다.
ImapMessageInfo.UniqueId 속성: 메시지의 고유 식별자를 가져옵니다.
Aspose.Email.MailMessage.ItemId 속성: 메일함 내 메시지에 대한 추가 식별 정보를 나타냅니다.
다음 코드 조각은 IMAP 메일함의 메시지 식별 정보를 얻는 방법을 보여줍니다:
- 다음의 인스턴스를 생성합니다. ImapClient IMAP 서버 호스트, 포트, 이메일 주소, 비밀번호 및 보안 옵션과 같은 필요한 매개변수를 제공하여 사용하는 클래스.
- 다음 사용 ListMessages "INBOX" 폴더에서 메시지 목록을 검색하는 메서드. Take(5) 메서드를 사용하여 처음 5개의 메시지로 목록을 제한합니다.
- 다음 방법을 사용하여 나열된 메시지의 시퀀스 번호를 추출합니다 SequenceNumber 각 메시지의 속성.
- 다음 사용 FetchMessages 앞 단계에서 얻은 시퀀스 번호를 사용하여 서버에서 메시지의 전체 세부 정보를 검색하는 메서드.
- 가져온 메시지를 순회하면서 각 메시지에 대해 다음 정보를 검색하고 표시합니다:
- 메시지의 시퀀스 번호.
- ItemId.SequenceNumber 속성.
- 메시지의 제목.
using (var client = new ImapClient(imapHost, port, emailAddress, password, securityOption))
{
// List the first 5 messages from the inbox
var msgs = client.ListMessages("INBOX").Take(5);
// Get sequence numbers of the messages
var seqIds = msgs.Select(t => t.SequenceNumber);
// Fetch messages based on sequence numbers
var msgsViaFetch = client.FetchMessages(seqIds);
for (var i = 0; i < 5; i++)
{
var thisMsg = msgsViaFetch[i];
Console.WriteLine($"Message ID: {seqIds.ElementAt(i)} SequenceNumber: {thisMsg.ItemId.SequenceNumber} Subject: {thisMsg.Subject}");
}
}
서버에서 MIME 메시지 ID 목록
ImapMessageInfo MIME을 제공합니다 MessageId 전체 메시지를 추출하지 않고 메시지를 식별하기 위해 사용됩니다. 다음 코드 스니펫은 MIME messageId를 나열하는 방법을 보여줍니다.
ImapClient client = new ImapClient();
client.Host = "domain.com";
client.Username = "username";
client.Password = "password";
try
{
ImapMessageInfoCollection messageInfoCol = client.ListMessages("Inbox");
foreach (ImapMessageInfo info in messageInfoCol)
{
// Display MIME Message ID
Console.WriteLine("Message Id = " + info.MessageId);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
서버에서 메시지 목록 가져오기
Aspose.Email은 2개의 멤버를 오버로드한 변형을 제공합니다. ListMessages() 쿼리를 기반으로 지정된 수의 메시지를 검색합니다. 다음 코드 조각은 메시지를 나열하는 방법을 보여줍니다.
imapClient.SelectFolder("Inbox");
ImapQueryBuilder builder = new ImapQueryBuilder();
MailQuery query =
builder.Or(
builder.Or(
builder.Or(
builder.Or(
builder.Subject.Contains(" (1) "),
builder.Subject.Contains(" (2) ")),
builder.Subject.Contains(" (3) ")),
builder.Subject.Contains(" (4) ")),
builder.Subject.Contains(" (5) "));
ImapMessageInfoCollection messageInfoCol4 = imapClient.ListMessages(query, 4);
Console.WriteLine((messageInfoCol4.Count == 4) ? "Success" : "Failure");
재귀적으로 메시지 나열
IMAP 프로토콜은 메일함 폴더에서 메시지를 재귀적으로 나열하는 것을 지원합니다. 이는 폴더의 하위 폴더에서도 메시지를 나열하는 데 도움이 됩니다. 다음 코드 스니펫은 메시지를 재귀적으로 나열하는 방법을 보여줍니다.
// Create an imapclient with host, user and password
ImapClient client = new ImapClient();
client.Host = "domain.com";
client.Username = "username";
client.Password = "password";
client.SelectFolder("InBox");
ImapMessageInfoCollection msgsColl = client.ListMessages(true);
Console.WriteLine("Total Messages: " + msgsColl.Count);
다중 연결을 통한 메시지 목록
ImapClient 를 제공합니다. UseMultiConnection 무거운 작업을 위해 다중 연결을 생성하는 데 사용할 수 있는 속성입니다. 멀티연결 모드에서 사용할 연결 수는 다음을 사용하여 설정할 수 있습니다. ImapClient.ConnectionsQuantity. 다음 코드 스니펫은 다중 연결 모드를 사용하여 메시지를 나열하고 단일 연결 모드와 성능을 비교하는 예를 보여줍니다.
ImapClient imapClient = new ImapClient();
imapClient.Host = "<HOST>";
imapClient.Port = 993;
imapClient.Username = "<USERNAME>";
imapClient.Password = "<PASSWORD>";
imapClient.SupportedEncryption = EncryptionProtocols.Tls;
imapClient.SecurityOptions = SecurityOptions.SSLImplicit;
imapClient.SelectFolder("Inbox");
imapClient.ConnectionsQuantity = 5;
imapClient.UseMultiConnection = MultiConnectionMode.Enable;
DateTime multiConnectionModeStartTime = DateTime.Now;
ImapMessageInfoCollection messageInfoCol1 = imapClient.ListMessages(true);
TimeSpan multiConnectionModeTimeSpan = DateTime.Now - multiConnectionModeStartTime;
imapClient.UseMultiConnection = MultiConnectionMode.Disable;
DateTime singleConnectionModeStartTime = DateTime.Now;
ImapMessageInfoCollection messageInfoCol2 = imapClient.ListMessages(true);
TimeSpan singleConnectionModeTimeSpan = DateTime.Now - singleConnectionModeStartTime;
double performanceRelation = singleConnectionModeTimeSpan.TotalMilliseconds / multiConnectionModeTimeSpan.TotalMilliseconds;
Console.WriteLine("Performance Relation: " + performanceRelation);
페이지 지원을 통한 메시지 목록
이메일 서버에 메일함에 대량의 메시지가 포함된 경우, 페이지 지원을 통해 메시지를 나열하거나 검색하려는 경우가 종종 있습니다. Aspose.Email API의 ImapClient 페이지 지원을 통해 서버에서 메시지를 검색할 수 있게 합니다.
///<summary>
/// This example shows the paging support of ImapClient for listing messages from the server
/// Available in Aspose.Email for .NET 6.4.0 and onwards
///</summary>
using (ImapClient client = new ImapClient("host.domain.com", 993, "username", "password"))
{
try
{
int messagesNum = 12;
int itemsPerPage = 5;
MailMessage message = null;
// Create some test messages and append these to server's inbox
for (int i = 0; i < messagesNum; i++)
{
message = new MailMessage(
"from@domain.com",
"to@domain.com",
"EMAILNET-35157 - " + Guid.NewGuid(),
"EMAILNET-35157 Move paging parameters to separate class");
client.AppendMessage(ImapFolderInfo.InBox, message);
}
// List messages from inbox
client.SelectFolder(ImapFolderInfo.InBox);
ImapMessageInfoCollection totalMessageInfoCol = client.ListMessages();
// Verify the number of messages added
Console.WriteLine(totalMessageInfoCol.Count);
////////////////// RETREIVE THE MESSAGES USING PAGING SUPPORT////////////////////////////////////
List<ImapPageInfo> pages = new List<ImapPageInfo>();
PageSettings pageSettings = new PageSettings();
ImapPageInfo pageInfo = client.ListMessagesByPage(itemsPerPage, 0, pageSettings);
Console.WriteLine(pageInfo.TotalCount);
pages.Add(pageInfo);
while (!pageInfo.LastPage)
{
pageInfo = client.ListMessagesByPage(itemsPerPage, pageInfo.NextPage.PageOffset, pageSettings);
pages.Add(pageInfo);
}
int retrievedItems = 0;
foreach (ImapPageInfo folderCol in pages)
retrievedItems += folderCol.Items.Count;
Console.WriteLine(retrievedItems);
}
finally
{
}
}
메시지 첨부 파일 나열
첨부 파일의 이름, 크기 등의 정보를 실제 첨부 데이터를 가져오지 않고 얻으려면 다음 API를 사용하십시오:
- Aspose.Email.Clients.Imap.ImapAttachmentInfo - 첨부 파일 정보를 나타냅니다.
- Aspose.Email.Clients.Imap.ImapAttachmentInfoCollection - 컬렉션을 나타냅니다. ImapAttachmentInfo 클래스.
- Aspose.Email.Clients.Imap.ListAttachments(int sequenceNumber) - 메시지의 각 첨부 파일에 대한 정보를 가져옵니다.
아래 단계가 포함된 코드 샘플은 API 사용 방법을 보여줍니다:
- 다음을 호출합니다. ListMessages() imapClient 객체의 메서드입니다. 이 메서드는 메일함에 있는 메시지 정보를 포함하는 ImapMessageInfoCollection을 반환합니다.
- foreach 루프를 사용하여 messageInfoCollection의 각 메시지를 순회합니다.
- 다음을 호출합니다. ListAttachments() imapClient 객체의 메서드이며, 메시지 객체의 SequenceNumber 속성을 매개변수로 전달합니다. 이 메서드는 메시지의 첨부 파일 정보를 포함하는 ImapAttachmentInfoCollection을 반환합니다.
- foreach 루프를 사용하여 attachmentInfoCollection의 각 첨부 파일을 순회합니다.
- 내부 루프에서, attachmentInfo 객체의 속성을 사용하여 각 첨부 파일에 대한 정보를 액세스할 수 있습니다.
var messageInfoCollection = imapClient.ListMessages();
foreach (var message in messageInfoCollection)
{
var attachmentInfoCollection = imapClient.ListAttachments(message.SequenceNumber);
foreach (var attachmentInfo in attachmentInfoCollection)
{
Console.WriteLine("Attachment: {0} (size: {1})", attachmentInfo.Name, attachmentInfo.Size);
}
}
메시지 가져오기 및 저장
서버에서 메시지 가져오기
다음은 ImapClient 클래스는 IMAP 서버에서 메시지를 가져와 EML 형식으로 로컬 디스크에 저장할 수 있습니다. 메시지를 디스크에 저장하려면 다음 단계가 필요합니다:
- 다음의 인스턴스를 생성합니다. ImapClient 클래스.
- ImapClient에 호스트 이름, 포트, 사용자 이름 및 비밀번호를 지정합니다 생성자.
- 다음으로 폴더를 선택합니다 SelectFolder() 메서드.
- 다음을 호출합니다. ListMessages 메서드로 가져옵니다 ImapMessageInfoCollection 객체.
- 다음에 대해 반복합니다 ImapMessageInfoCollection 컬렉션에서, 다음을 호출합니다 SaveMessage() 메서드를 호출하고 출력 경로와 파일 이름을 제공하십시오.
다음 코드 스니펫은 서버에서 이메일 메시지를 가져와 저장하는 방법을 보여줍니다.
// Select the inbox folder and Get the message info collection
client.SelectFolder(ImapFolderInfo.InBox);
ImapMessageInfoCollection list = client.ListMessages();
// Download each message
for (int i = 0; i < list.Count; i++)
{
// Save the EML file locally
client.SaveMessage(list[i].UniqueId, dataDir + list[i].UniqueId + ".eml");
}
내림차순으로 메시지 가져오기
Aspose.Email은 ImapClient.ListMessagesByPage 메서드 - 페이지 지원으로 메시지를 나열하는 메서드. 일부 오버로드는 ImapClient.ListMessagesByPage 받아들입니다 PageSettings 매개변수로. PageSettings 을 제공합니다 AscendingSorting 이 속성을 false 로 설정하면 이메일이 내림차순으로 반환됩니다.
다음 예제 코드는 다음 사용을 보여줍니다 AscendingSorting 속성 PageSettings 이메일 순서를 변경하는 클래스.
ImapClient imapClient = new ImapClient();
imapClient.Host = "<HOST>";
imapClient.Port = 993;
imapClient.Username = "<USERNAME>";
imapClient.Password = "<PASSWORD>";
imapClient.SupportedEncryption = EncryptionProtocols.Tls;
imapClient.SecurityOptions = SecurityOptions.SSLImplicit;
PageSettings pageSettings = new PageSettings { AscendingSorting = false };
ImapPageInfo pageInfo = imapClient.ListMessagesByPage(5, pageSettings);
ImapMessageInfoCollection messages = pageInfo.Items;
foreach (ImapMessageInfo message in messages)
{
Console.WriteLine(message.Subject + " -> " + message.Date.ToString());
}
MSG 형식으로 메시지 저장
이메일을 MSG 형식으로 저장하려면, ImapClient.FetchMessage() 메서드를 호출해야 합니다. 이 메서드는 메시지를 다음 인스턴스로 반환합니다 MailMessage 클래스. MailMessage.Save() 메서드를 호출하여 메시지를 MSG로 저장할 수 있습니다. 다음 코드 스니펫은 MSG 형식으로 메시지를 저장하는 방법을 보여줍니다.
// The path to the file directory.
string dataDir = RunExamples.GetDataDir_IMAP();
// Create an imapclient with host, user and password
ImapClient client = new ImapClient("localhost", "user", "password");
// Select the inbox folder and Get the message info collection
client.SelectFolder(ImapFolderInfo.InBox);
ImapMessageInfoCollection list = client.ListMessages();
// Download each message
for (int i = 0; i < list.Count; i++)
{
// Save the message in MSG format
MailMessage message = client.FetchMessage(list[i].UniqueId);
message.Save(dataDir + list[i].UniqueId + "_out.msg", SaveOptions.DefaultMsgUnicode);
}
가져온 메시지 그룹화
ImapClient 를 제공합니다. FetchMessages 시퀀스 번호 또는 고유 ID의 iterable을 받아 리스트를 반환하는 메서드. MailMessage. 다음 코드 스니펫은 ~의 사용을 보여줍니다. FetchMessages 시퀀스 번호와 고유 ID로 메시지를 가져오는 메서드.
ImapClient imapClient = new ImapClient();
imapClient.Host = "<HOST>";
imapClient.Port = 993;
imapClient.Username = "<USERNAME>";
imapClient.Password = "<PASSWORD>";
imapClient.SupportedEncryption = EncryptionProtocols.Tls;
imapClient.SecurityOptions = SecurityOptions.SSLImplicit;
ImapMessageInfoCollection messageInfoCol = imapClient.ListMessages();
Console.WriteLine("ListMessages Count: " + messageInfoCol.Count);
int[] sequenceNumberAr = messageInfoCol.Select((ImapMessageInfo mi) => mi.SequenceNumber).ToArray();
string[] uniqueIdAr = messageInfoCol.Select((ImapMessageInfo mi) => mi.UniqueId).ToArray();
IList<MailMessage> fetchedMessagesBySNumMC = imapClient.FetchMessages(sequenceNumberAr);
Console.WriteLine("FetchMessages-sequenceNumberAr Count: " + fetchedMessagesBySNumMC.Count);
IList<MailMessage> fetchedMessagesByUidMC = imapClient.FetchMessages(uniqueIdAr);
Console.WriteLine("FetchMessages-uniqueIdAr Count: " + fetchedMessagesByUidMC.Count);
폴더를 가져오고 메시지를 재귀적으로 읽기
이 문서에서는 대부분의 ImapClient 이 기능들은 IMAP 서버에서 모든 폴더와 하위 폴더를 재귀적으로 나열하는 애플리케이션을 만들 때 사용됩니다. 또한 각 폴더와 하위 폴더의 메시지를 로컬 디스크에 MSG 형식으로 저장합니다. 디스크에 폴더와 메시지는 IMAP 서버와 동일한 계층 구조로 생성 및 저장됩니다. 아래 코드 스니펫은 메시지와 하위 폴더 정보를 재귀적으로 얻는 방법을 보여줍니다.
public static void Run()
{
// Create an instance of the ImapClient class
ImapClient client = new ImapClient();
// Specify host, username, password, Port and SecurityOptions for your client
client.Host = "imap.gmail.com";
client.Username = "your.username@gmail.com";
client.Password = "your.password";
client.Port = 993;
client.SecurityOptions = SecurityOptions.Auto;
try
{
// The root folder (which will be created on disk) consists of host and username
string rootFolder = client.Host + "-" + client.Username;
// Create the root folder and List all the folders from IMAP server
Directory.CreateDirectory(rootFolder);
ImapFolderInfoCollection folderInfoCollection = client.ListFolders();
foreach (ImapFolderInfo folderInfo in folderInfoCollection)
{
// Call the recursive method to read messages and get sub-folders
ListMessagesInFolder(folderInfo, rootFolder, client);
}
// Disconnect to the remote IMAP server
client.Dispose();
}
catch (Exception ex)
{
Console.Write(Environment.NewLine + ex);
}
Console.WriteLine(Environment.NewLine + "Downloaded messages recursively from IMAP server.");
}
/// Recursive method to get messages from folders and sub-folders
private static void ListMessagesInFolder(ImapFolderInfo folderInfo, string rootFolder, ImapClient client)
{
// Create the folder in disk (same name as on IMAP server)
string currentFolder = RunExamples.GetDataDir_IMAP();
Directory.CreateDirectory(currentFolder);
// Read the messages from the current folder, if it is selectable
if (folderInfo.Selectable)
{
// Send status command to get folder info
ImapFolderInfo folderInfoStatus = client.GetFolderInfo(folderInfo.Name);
Console.WriteLine(folderInfoStatus.Name + " folder selected. New messages: " + folderInfoStatus.NewMessageCount + ", Total messages: " + folderInfoStatus.TotalMessageCount);
// Select the current folder and List messages
client.SelectFolder(folderInfo.Name);
ImapMessageInfoCollection msgInfoColl = client.ListMessages();
Console.WriteLine("Listing messages....");
foreach (ImapMessageInfo msgInfo in msgInfoColl)
{
// Get subject and other properties of the message
Console.WriteLine("Subject: " + msgInfo.Subject);
Console.WriteLine("Read: " + msgInfo.IsRead + ", Recent: " + msgInfo.Recent + ", Answered: " + msgInfo.Answered);
// Get rid of characters like ? and :, which should not be included in a file name and Save the message in MSG format
string fileName = msgInfo.Subject.Replace(":", " ").Replace("?", " ");
MailMessage msg = client.FetchMessage(msgInfo.SequenceNumber);
msg.Save(currentFolder + "\\" + fileName + "-" + msgInfo.SequenceNumber + ".msg", SaveOptions.DefaultMsgUnicode);
}
Console.WriteLine("============================\n");
}
else
{
Console.WriteLine(folderInfo.Name + " is not selectable.");
}
try
{
// If this folder has sub-folders, call this method recursively to get messages
ImapFolderInfoCollection folderInfoCollection = client.ListFolders(folderInfo.Name);
foreach (ImapFolderInfo subfolderInfo in folderInfoCollection)
{
ListMessagesInFolder(subfolderInfo, rootFolder, client);
}
}
catch (Exception) { }
}
특수 메시지 정보 처리
요약 정보로 추가 매개변수 가져오기
using (ImapClient client = new ImapClient("host.domain.com", "username", "password"))
{
MailMessage message = new MailMessage("from@domain.com", "to@doman.com", "EMAILNET-38466 - " + Guid.NewGuid().ToString(), "EMAILNET-38466 Add extra parameters for UID FETCH command");
// append the message to the server
string uid = client.AppendMessage(message);
// wait for the message to be appended
Thread.Sleep(5000);
// Define properties to be fetched from server along with the message
string[] messageExtraFields = new string[] { "X-GM-MSGID", "X-GM-THRID" };
// retreive the message summary information using it's UID
ImapMessageInfo messageInfoUID = client.ListMessage(uid, messageExtraFields);
// retreive the message summary information using it's sequence number
ImapMessageInfo messageInfoSeqNum = client.ListMessage(1, messageExtraFields);
// List messages in general from the server based on the defined properties
ImapMessageInfoCollection messageInfoCol = client.ListMessages(messageExtraFields);
ImapMessageInfo messageInfoFromList = messageInfoCol[0];
// verify that the parameters are fetched in the summary information
foreach (string paramName in messageExtraFields)
{
Console.WriteLine(messageInfoFromList.ExtraParameters.ContainsKey(paramName));
Console.WriteLine(messageInfoUID.ExtraParameters.ContainsKey(paramName));
Console.WriteLine(messageInfoSeqNum.ExtraParameters.ContainsKey(paramName));
}
}
List-Unsubscribe 헤더 정보 가져오기
List-Unsubscribe 헤더에는 광고, 뉴스레터 등 메일링 리스트 구독 해지를 위한 URL이 포함됩니다. List-Unsubscribe 헤더를 가져오려면 다음을 사용하세요 ListUnsubscribe 속성 ImapMessageInfo 클래스. 다음 예제는 사용법을 보여줍니다 ListUnsubscribe List-Unsubscribe 헤더를 가져오는 속성.
ImapClient imapClient = new ImapClient();
imapClient.Host = "<HOST>";
imapClient.Port = 993;
imapClient.Username = "<USERNAME>";
imapClient.Password = "<PASSWORD>";
imapClient.SupportedEncryption = EncryptionProtocols.Tls;
imapClient.SecurityOptions = SecurityOptions.SSLImplicit;
ImapMessageInfoCollection messageInfoCol = imapClient.ListMessages();
foreach (ImapMessageInfo imapMessageInfo in messageInfoCol)
{
Console.WriteLine("ListUnsubscribe Header: " + imapMessageInfo.ListUnsubscribe);
}