You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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.

Step 1: Verify Active Connection & Select Target Folder

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;
}
Step 2: Retrieve Email Messages

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);
Step 3: Parse & Save Email Content

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("------------------------");
}
Key Notes & Tips
  • Error Handling: Wrap all this code in try-catch blocks 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.ReadWrite and set message.IsSeen = true;, then call message.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:08:19