.NET 接收郵件

引用的包信息

<PackageReference Include="MailKit" Version="4.14.1" />

代碼

using MailKit;
using MailKit.Net.Imap;
using MailKit.Net.Pop3;
using MailKit.Search;
using MimeKit;

public class Program
{
    static int _lastPop3Count = 0;
    public static async Task Main(string[] args)
    {
        string protocol = "IMAP";
        string host = "imap.qq.com";
        int port = 993;
        // 目前只測試了扣扣郵箱其他的收不到126,163、outlook等
        string username = "example@qq.com";
        string password = "password";
        int checkInterval = 5;
        bool useSsl = true;

        // 3. 初始化控制臺
        Console.Title = "MailKit 郵箱監(jiān)控程序 - .NET Core";
        Console.WriteLine("======================================");
        Console.WriteLine("郵箱監(jiān)控程序已啟動(.NET Core)!");
        Console.WriteLine($"協(xié)議:{protocol} | 郵箱:{username}");
        Console.WriteLine($"檢查間隔:{checkInterval}秒");
        Console.WriteLine("======================================");
        Console.WriteLine("按 ESC 鍵退出程序...\n");

        // 4. 退出令牌(.NET Core 優(yōu)雅退出方案)
        var cts = new CancellationTokenSource();
        // 后臺線程監(jiān)聽ESC鍵退出
        _ = Task.Run(() =>
        {
            while (Console.ReadKey(true).Key != ConsoleKey.Escape) { }
            Console.WriteLine("\n程序正在退出...");
            cts.Cancel(); // 觸發(fā)取消令牌
        });

        // 5. 核心監(jiān)控邏輯(循環(huán)檢查,支持取消)
        try
        {
            while (!cts.Token.IsCancellationRequested)
            {
                try
                {
                    if (protocol.Equals("IMAP", StringComparison.OrdinalIgnoreCase))
                    {
                        await CheckImapEmailsAsync(host, port, username, password, useSsl);
                    }
                    else
                    {
                        await CheckPop3EmailsAsync(host, port, username, password, useSsl);
                    }
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 監(jiān)控異常:{ex.Message}");
                    Console.ResetColor();
                }

                // 等待間隔(支持取消)
                await Task.Delay(TimeSpan.FromSeconds(checkInterval), cts.Token);
            }
        }
        catch(OperationCanceledException ex)
        {
            // 正常取消,無異常
            ;
        }

        Console.WriteLine("程序已退出!");
    }

    /// <summary>
    /// IMAP協(xié)議:精準獲取未讀郵件(推薦)
    /// </summary>
    public static async Task CheckImapEmailsAsync(string host, int port, string username, string password, bool useSsl)
    {
        using var client = new ImapClient();
        // 異步連接(.NET Core 推薦異步操作)
        await client.ConnectAsync(host, port, useSsl);
        await client.AuthenticateAsync(username, password);

        var inbox = client.Inbox;
        await inbox.OpenAsync(FolderAccess.ReadOnly);

        Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 檢查收件箱:總計 {inbox.Count} 封郵件");

        // 搜索未讀郵件
        var unreadMessages = await inbox.SearchAsync(SearchQuery.NotSeen);
        if (unreadMessages.Count > 0)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"發(fā)現(xiàn) {unreadMessages.Count} 封未讀郵件:\n");
            Console.ResetColor();

            foreach (var uid in unreadMessages)
            {
                var message = await inbox.GetMessageAsync(uid);
                PrintEmailInfo(message, uid.ToString());

                // 可選:標記為已讀
                // await inbox.AddFlagsAsync(uid, MessageFlags.Seen, true);
            }
        }
        else
        {
            Console.WriteLine("暫無未讀郵件\n");
        }

        await client.DisconnectAsync(true);
    }

    /// <summary>
    /// POP3協(xié)議:兼容模式
    /// </summary>
    public static async Task CheckPop3EmailsAsync(string host, int port, string username, string password, bool useSsl)
    {
        using var client = new Pop3Client();
        await client.ConnectAsync(host, port, useSsl);
        await client.AuthenticateAsync(username, password);

        int totalCount = client.Count;
        Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 檢查收件箱:總計 {totalCount} 封郵件");

        if (totalCount > _lastPop3Count)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"發(fā)現(xiàn) {totalCount - _lastPop3Count} 封新郵件:\n");
            Console.ResetColor();

            for (int i = _lastPop3Count + 1; i <= totalCount; i++)
            {
                var message = await client.GetMessageAsync(i);
                PrintEmailInfo(message, i.ToString());
            }
            _lastPop3Count = totalCount;
        }
        else
        {
            Console.WriteLine("暫無新郵件\n");
        }

        await client.DisconnectAsync(true);
    }

    /// <summary>
    /// 格式化輸出郵件信息
    /// </summary>
    public static void PrintEmailInfo(MimeMessage message, string id)
    {
        Console.WriteLine($"---------- 郵件 [{id}] ----------");
        Console.WriteLine($"發(fā)件人:{message.From}");
        Console.WriteLine($"收件人:{message.To}");
        Console.WriteLine($"標題:{message.Subject}");
        Console.WriteLine($"時間:{message.Date:yyyy-MM-dd HH:mm:ss}");

        // 解析純文本正文
        var body = message.TextBody ?? "無純文本正文";
        Console.WriteLine($"正文:{body.Substring(0, Math.Min(body.Length, 200))}...");
        Console.WriteLine("----------------------------------\n");
    }
}

預(yù)覽

======================================
郵箱監(jiān)控程序已啟動(.NET Core)!
協(xié)議:IMAP | 郵箱:wx167788@qq.com
檢查間隔:5秒
======================================
按 ESC 鍵退出程序...

[2026-01-12 08:48:44] 檢查收件箱:總計 0 封郵件
暫無未讀郵件

[2026-01-12 08:48:50] 檢查收件箱:總計 1 封郵件
發(fā)現(xiàn) 1 封未讀郵件:

---------- 郵件 [513] ----------
發(fā)件人:"Charles" <412102100@qq.com>
收件人:"wx167788" <wx167788@qq.com>
標題:Test
時間:2026-01-12 08:48:10
正文:Test




Charles
412102100@qq.com...
----------------------------------
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容