ดึงและแสดงรายการอีเมลจากเซิร์ฟเวอร์ IMAP
การดึงและแสดงรายการข้อความ
วิธีรับข้อมูลการระบุของข้อความในกล่องจดหมาย
เมื่อดึงและประมวลผลข้อความอีเมล คุณสามารถรับข้อมูลการระบุอย่างละเอียด เช่น หมายเลขลำดับและ ID ที่ไม่ซ้ำได้โดยใช้คุณลักษณะต่อไปนี้ที่ให้โดยเวอร์ชันล่าสุดของ Aspose.Email สำหรับ .NET:
Aspose.Email.ImapMessageInfo คลาส: แสดงข้อมูลการระบุของข้อความในกล่องจดหมาย IMAP.
ImapMessageInfo.SequenceNumber คุณสมบัติ: ดึงหมายเลขลำดับของข้อความ
ImapMessageInfo.UniqueId คุณสมบัติ: ดึงตัวระบุที่ไม่ซ้ำของข้อความ
Aspose.Email.MailMessage.ItemId คุณสมบัติ: แสดงข้อมูลการระบุเพิ่มเติมของข้อความภายในกล่องจดหมาย
ตัวอย่างโค้ดต่อไปนี้แสดงวิธีรับข้อมูลการระบุข้อความในกล่องจดหมาย IMAP:
- สร้างอินสแตนซ์ของ ImapClient คลาสโดยให้พารามิเตอร์ที่จำเป็นเช่น โฮสต์เซิร์ฟเวอร์ IMAP, พอร์ต, ที่อยู่อีเมล, รหัสผ่าน, และตัวเลือกความปลอดภัย
- ใช้ ListMessages วิธีการดึงรายการข้อความจากโฟลเดอร์ "INBOX" จำกัดรายการที่ 5 ข้อความแรกด้วยเมธอด Take(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}");
}
}
แสดงรายการ ID ของข้อความ MIME จากเซิร์ฟเวอร์
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 มีรูปแบบ overload 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);
แสดงรายการข้อความด้วย MultiConnection
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);
แสดงรายการข้อความด้วยการสนับสนุนการแบ่งหน้า
ในสถานการณ์ที่เซิร์ฟเวอร์อีเมลมีข้อความจำนวนมากในกล่องจดหมาย บ่อยครั้งที่ต้องการแสดงรายการหรือดึงข้อความโดยมีการสนับสนุนการแบ่งหน้า API ของ Aspose.Email 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 ที่มีข้อมูลเกี่ยวกับข้อความในกล่องจดหมาย
- ทำการวนซ้ำแต่ละข้อความใน messageInfoCollection ด้วยลูป foreach
- เรียกใช้ ListAttachments() เมธอดบนอ็อบเจกต์ imapClient โดยส่งคุณสมบัติ SequenceNumber ของอ็อบเจกต์ข้อความเป็นพารามิเตอร์ เมธอดนี้จะคืนค่า ImapAttachmentInfoCollection ที่มีข้อมูลเกี่ยวกับไฟล์แนบในข้อความ
- ทำการวนซ้ำแต่ละไฟล์แนบใน attachmentInfoCollection ด้วยลูป foreach
- ภายในลูปภายใน คุณสามารถเข้าถึงข้อมูลของแต่ละไฟล์แนบโดยใช้คุณสมบัติของอ็อบเจกต์ 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 จะคืนค่าอีเมลในลำดับ descending
โค้ดตัวอย่างต่อไปนี้สาธิตการใช้ของ 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 เมธอดที่รับ iterable ของลำดับหมายเลขหรือ Unique ID และคืนค่าเป็นรายการของ 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);
}