以前使用OpenPop测试电子邮件通知。切换到IMAP并立即开始查看MailKit。我目前在从Gmail检索电子邮件正文的纯字符串文本时遇到问题。
到目前为止我的代码片段:
using (var client = new ImapClient())
{
var credentials = new NetworkCredential("username", "password");
var uri = new Uri("imaps://imap.gmail.com");
client.Connect(uri);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(credentials);
client.Inbox.Open(FolderAccess.ReadOnly);
var inboxMessages = client.Inbox.Fetch(0, -1, MessageSummaryItems.Full).ToList();
foreach (var message in inboxMessages)
{
var messageBody = message.TextBody.ToString();
...
}
...
}
根据我对文档的理解,到目前为止TextBody可以以纯文本形式检索消息正文(如果存在)。但是在Visual Studio中进行调试时,我发现这是TextBody的值。
{(" TEXT"" PLAIN"(" CHARSET"" utf-8""格式"&# 34;流动")NIL NIL" 7BIT" 6363 NIL NIL NIL NIL 119)}
我在某处失踪了吗?这是否意味着从MailKit的角度来看,身体缺失了?我也看到了HtmlBody的相似值。
答案 0 :(得分:1)
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
枚举参数视为位域,其中枚举值可以是按位的 - 或者一起指定要IMessageSummary
查询填充的Fetch
个属性。
在上面的示例中,UniqueId
和Body
位标志指定我们要填充UniqueId
结果的Body
和IMessageSummary
属性。< / p>
如果我们想获取有关已读/未读状态等的信息,我们会将MessageSummaryItems.Flags
添加到列表中。
注意:Body
和BodyStructure
枚举值都填充了IMessageSummary.Body
属性,但BodyStructure
包含了确定身体部位是否为依恋与否等等。