如何使用 MailKit 库获取我对电子邮件的回复?

How to Get My Replies on an email using MailKit library?

我正在使用 MailKit 库从 IMAP 服务器获取消息。

我试图根据其主题获取一封电子邮件,但它只有 returns 个客户端消息的 ID,而没有我的回复

var uidsX = client.Inbox.Search (SearchQuery.SubjectContains ("Message\'s Subject"));

我还尝试 hard-code 从 Gmail 获取消息 ID header 的值,但我收到了一个空列表!

const string myReplyId = @"<CAAWrOQmJib_RHUn+3vB9GqATim165zq_Upn_8OTatZZMYGtf5w@mail.gmail.com>";
var myReply = client.Inbox.Search(SearchQuery.HeaderContains("Message-ID", myMessageId));

我什至尝试查看是否可以在“已发送文件夹”而不是“收件箱”中找到我的回复,但我得到的是一个空列表。

那么有人可以帮助我吗?

首先,我需要确保我正确理解了您所说的您正在尝试“通过电子邮件回复”的意思。

我假设你现在的意思是有人给你发了一条消息(我们称他为乔),你回复了他,你想编写一个程序来连接到 IMAP 服务器并下载你的回复给乔。

假设消息的主题是“饮料?”

换句话说:

From: Joe <joe@example.com>
To: Malek <malek@example.com>
Subject: drinks?
Message-Id: <msgid-1@example.com>

Hey Malek, wanna grab drinks after work tonight?

...然后你回复了他:

From: Malek <malek@example.com>
To: Joe <joe@example.com>
Subject: Re: drinks?
Message-Id: <msgid-2@example.com>
References: <msgid-1@example.com>
In-Reply-To: <msgid-1@example.com>

Can't tonight, but how about after work Friday?

您正在自己的收件箱文件夹中搜索包含“Re: drinks?”的邮件。并以没有匹配结束?您还尝试使用 Message-Id 值在收件箱中搜索邮件,但没有找到匹配项?

最有可能的是,这不会起作用,因为您用来发送回复的任何客户端都可能最终没有出现在收件箱中,它可能最终出现在“已发送”文件夹中(或位于您硬盘上的本地“已发送”文件夹中驱动器)。

您提到您还尝试搜索“已发送”文件夹,但仍然 没有找到匹配项,这表明邮件不存在。如果您使用桌面邮件客户端发送它,它可能在您的硬盘上(通常桌面客户端可以配置为将发送的邮件保存在服务器上,但有时它们默认为本地硬盘)。

如果您使用 MailKit 的 SmtpClient 发送邮件(或 System.Net.Mail 的 SmtpClient),则该邮件不会保存在任何地方 - 因此它也不在您的“已发送”文件夹中。

当 SMTP 服务器收到要发送的消息时,它不会将其复制到您的“已发送”文件夹中。这必须使用 IMAP 来完成。

下面是我使用 MailKit 的方式。将 msg 替换为您要回复的收件箱文件夹消息。


MessageSummaryItems pullSummaries = MessageSummaryItems.Envelope | MessageSummaryItems.Flags | MessageSummaryItems.InternalDate | MessageSummaryItems.Size | MessageSummaryItems.UniqueId | MessageSummaryItems.GMailLabels | MessageSummaryItems.BodyStructure;

//Open the sent mailbox
await ((ImapFolder)Client.GetFolder(SpecialFolder.Sent)).OpenAsync(FolderAccess.ReadOnly, CancelToken.Token);

//Query the message by the InReplyTo header
var replMsg = await SentFolder.SearchAsync(SearchQuery.HeaderContains("In-Reply-To", msg.Envelope.MessageId));
if (replMsg.Count() > 0)
{
   var replFetch = await SentFolder.FetchAsync(replMsg, pullSummaries);
   foreach (var sentItem in replFetch)
   {
      MimeMessage RepliedEmail = await SentFolder.GetMessageAsync(sentItem.Index);
      Console.WriteLine($"{RepliedEmail.Subject} from {string.Join(",", RepliedEmail.From.OfType<MailboxAddress>().Select(f => $"{f.Name} <{f.Address}>").ToArray())}");
      Console.WriteLine($"{RepliedEmail.GetTextBody(MimeKit.Text.TextFormat.Plain)}");
   }
                            
}