Fetch 方法仅获取有关消息的摘要信息,例如在邮件客户端中构建消息列表所需的信息。
如果要获取消息,需要使用GetMessage方法。
像这样:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate ("username", "password");
client.Inbox.Open (FolderAccess.ReadOnly);
var uids = client.Inbox.Search (SearchQuery.All);
foreach (var uid in uids) {
var message = client.Inbox.GetMessage (uid);
var text = message.TextBody;
Console.WriteLine ("This is the text/plain content:");
Console.WriteLine ("{0}", text);
}
client.Disconnect (true);
}
现在,如果您想仅下载消息正文,则需要使用您正在获取的摘要信息并将其作为参数传递给GetBodyPart 方法如下:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate ("username", "password");
client.Inbox.Open (FolderAccess.ReadOnly);
// Note: the Full and All enum values don't mean what you think
// they mean, they are aliases that match the IMAP aliases.
// You should also note that Body and BodyStructure have
// subtle differences and that you almost always want
// BodyStructure and not Body.
var items = client.Inbox.Fetch (0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
foreach (var item in items) {
if (item.TextBody != null) {
var mime = (TextPart) client.Inbox.GetBodyPart (item.UniqueId, item.TextBody);
var text = mime.Text;
Console.WriteLine ("This is the text/plain content:");
Console.WriteLine ("{0}", text);
}
}
client.Disconnect (true);
}
您可以将 Fetch 方法视为在 IMAP 服务器上执行 SQL 查询以获取消息的元数据,并将 MessageSummaryItems 枚举参数视为一个位域,其中枚举值可以按位或组合在一起指定您希望通过Fetch 查询填充哪些IMessageSummary 属性。
在上面的示例中,UniqueId 和 Body 位标志指定我们要填充 IMessageSummary 结果的 UniqueId 和 Body 属性。
如果我们想获取有关已读/未读状态等信息 - 我们会将MessageSummaryItems.Flags 添加到列表中。
注意:Body 和BodyStructure 枚举值都填充了IMessageSummary.Body 属性,但BodyStructure 包含确定正文部分是否为附件等所需的更多信息。