使用IMAPX库操作IMAP邮箱:下载邮件功能实现遇阻求助
Hey there! I’ve tinkered with IMAPX quite a bit, so let me share a complete, working implementation for downloading emails from a specific folder. I’ll walk you through each step with code examples to make this clear.
First, make sure your IMAPX client is still connected after login. Then, select the folder you want to pull emails from (since you already sorted out folder retrieval, this should fit right in):
// Assume 'client' is your already logged-in ImapClient instance var targetFolder = client.Folders.FirstOrDefault(f => f.Name.Equals("Inbox", StringComparison.OrdinalIgnoreCase)); if (targetFolder == null) { Console.WriteLine("Target folder not found!"); return; } // Open the folder with read-only access (use FolderAccess.ReadWrite if you need to mark emails as read) var folderOpened = targetFolder.Open(FolderAccess.ReadOnly); if (!folderOpened) { Console.WriteLine("Failed to open target folder!"); return; }
You can fetch all emails, or filter them using search queries (like unread, sent after a date, etc.). Here’s how to get all emails, plus a filtered example:
// Option 1: Fetch all emails in the folder var allMessages = targetFolder.Search(SearchQuery.All); // Option 2: Fetch only unread emails var unreadMessages = targetFolder.Search(SearchQuery.NotSeen); // Important: Fetch full message content (by default, only headers are retrieved) // Use FetchOptions to specify what you need (e.g., Body, Attachments, Headers) allMessages.Fetch(FetchOptions.All);
Now loop through each message to extract details like subject, sender, body, and save attachments if any:
foreach (var message in allMessages) { // Basic email details Console.WriteLine($"Subject: {message.Subject}"); Console.WriteLine($"From: {message.From}"); Console.WriteLine($"Sent Date: {message.Date:yyyy-MM-dd HH:mm}"); // Get email body (handle plain text and HTML) string bodyContent = string.Empty; if (!string.IsNullOrEmpty(message.Body.Text)) { bodyContent = message.Body.Text; // Save plain text body to file File.WriteAllText(@"C:\Emails\" + $"{message.Id}_body.txt", bodyContent); } else if (!string.IsNullOrEmpty(message.Body.Html)) { bodyContent = message.Body.Html; // Save HTML body to file File.WriteAllText(@"C:\Emails\" + $"{message.Id}_body.html", bodyContent); } // Save attachments (if any) if (message.Attachments.Any()) { var attachmentsDir = @"C:\Emails\Attachments\" + message.Id; Directory.CreateDirectory(attachmentsDir); foreach (var attachment in message.Attachments) { // Save attachment to disk attachment.Save(Path.Combine(attachmentsDir, attachment.FileName)); Console.WriteLine($"Saved attachment: {attachment.FileName}"); } } Console.WriteLine("------------------------"); }
- Error Handling: Wrap all this code in
try-catchblocks to handle IMAP connection drops, file access errors, etc. For example:try { // All the code above goes here } catch (ImapException ex) { Console.WriteLine($"IMAP Error: {ex.Message}"); } catch (IOException ex) { Console.WriteLine($"File System Error: {ex.Message}"); } - Pagination for Large Folders: If the folder has thousands of emails, fetching all at once can eat up memory. Use pagination instead:
int pageSize = 50; int totalMessages = targetFolder.Search(SearchQuery.All).Count; for (int i = 0; i < totalMessages; i += pageSize) { var pageMessages = targetFolder.Search(SearchQuery.All, i, pageSize); pageMessages.Fetch(FetchOptions.All); // Process pageMessages here } - Mark Emails as Read: If you want to mark fetched emails as read, open the folder with
FolderAccess.ReadWriteand setmessage.IsSeen = true;, then callmessage.Update();.
That should cover the full workflow for downloading emails from a folder with IMAPX. Let me know if you run into any specific edge cases!
内容的提问来源于stack exchange,提问作者user9404499

