使用 MailKit 将自定义 header 添加到电子邮件

Add custom header to email using MailKit

我目前正在使用以下代码下载邮件,向其中添加自定义 header,然后将该邮件添加回邮件文件夹:

using (ImapClient imap = new ImapClient())
{
    imap.ServerCertificateValidationCallback = (s, c, h, e) => true;
    imap.Connect(host, port, useSSL);

    imap.Authenticate(user, password);

    IMailFolder mailFolder = imap.GetFolder(folder);
    mailFolder.Open(FolderAccess.ReadWrite);

    if (mailFolder.Count > 0)
    {
        MimeMessage message = mailFolder.GetMessage(0);

        var header = message.Headers.FirstOrDefault(h => h.Field == "X-SomeCustomHeader");
        if (header == null)
        {
            message.Headers.Add("X-SomeCustomHeader", "SomeValue");
        }

        mailFolder.SetFlags(0, MessageFlags.Deleted, true);
        mailFolder.Expunge();

        UniqueId? newUid = mailFolder.Append(message);
        mailFolder.Expunge();

        var foundMails = mailFolder.Search(SearchQuery.HeaderContains("X-SomeCustomHeader", "SomeValue"));
        if (foundMails.Count > 0)
        {
            var foundMail = mailFolder.GetMessage(new UniqueId(foundMails.First().Id));

            Console.WriteLine(foundMail.Subject);
        }

        mailFolder.Close(true);
    }
}

此代码的问题是,如果我在文件夹中查看电子邮件的来源,header 不存在并且 foundMails 的计数为零。

如果我查看 message,它包含 header,所以如果我也查看 message.WriteTo(somePath);,那么 header 也在那里。

我做错了什么?

如果我使用 outlook 客户端,此代码有效,但在 gmail 客户端上使用时,它会失败。

问题是在 gmail 服务器上调用删除实际上并没有删除电子邮件。要解决此问题,请将电子邮件移至“垃圾箱”文件夹,然后将其删除。以下辅助方法可让您了解如何完成此操作:

protected void DeleteMessage(ImapClient imap, IMailFolder mailFolder, UniqueId uniqueId)
{
    if (_account.HostName.Equals("imap.gmail.com"))
    {
        IList<IMessageSummary> summaries = mailFolder.Fetch(new List<UniqueId>() { uniqueId }, MessageSummaryItems.GMailMessageId);
        if (summaries.Count != 1)
        {
            throw new Exception("Failed to find the message in the mail folder.");
        }

        mailFolder.MoveTo(uniqueId, imap.GetFolder(SpecialFolder.Trash));
        mailFolder.Close(true);

        IMailFolder trashMailFolder = imap.GetFolder(SpecialFolder.Trash);
        trashMailFolder.Open(FolderAccess.ReadWrite);

        SearchQuery query = SearchQuery.GMailMessageId(summaries[0].GMailMessageId.Value);

        IList<UniqueId> matches = trashMailFolder.Search(query);

        trashMailFolder.AddFlags(matches, MessageFlags.Deleted, true);
        trashMailFolder.Expunge(matches);

        trashMailFolder.Close(true);

        mailFolder.Open(FolderAccess.ReadWrite);
    }
    else
    {
        mailFolder.SetFlags(uniqueId, MessageFlags.Deleted, true);
        mailFolder.Expunge();
    }
}