MimeMessage
相当于 MailSystem.NET 的Message
对象,但这不是您想要的。您想要的是 MailKit IMessageSummary
,它允许您下载单个 MIME 部分(也称为“附件”)。
它还允许您非常快速地获取有关消息的摘要信息(标志、接收日期(又名“InternalDate”)预解析/解码的常见标头值(例如主题、发件人、收件人等),因为 IMAP 服务器具有这些部分缓存在其数据库中以便快速检索的信息。
using (var client = new ImapClient ()) {
client.Connect ("imap.mail-server.com", 993, SecureSocketOptions.SslOnConnect);
client.Authenticate ("username", "password");
// if you don't care about modifying message flags or deleting
// messages, you can open the INBOX in read-only mode...
client.Inbox.Open (FolderAccess.ReadOnly);
// search for messages sent since a particular date
var uids = client.Inbox.Search (SearchQuery.SentAfter (date));
// using the uids of the matching messages, fetch the BODYSTRUCTUREs
// of each message so that we can figure out which MIME parts to
// download individually.
foreach (var item in client.Inbox.Fetch (uids, MessageSummaryItems.BodyStructure MessageSummaryItems.UniqueId)) {
foreach (var attachment in item.Attachments.OfType<BodyPartBasic> ()) {
var part = (MimePart) client.Inbox.GetBodyPart (item.UniqueId, attachment);
using (var stream = File.Create (part.FileName))
part.ContentObject.DecodeTo (stream);
}
}
}
注意:每个属性IMessageSummary
都有一个相应的MessageSummaryItems
枚举值,您需要使用它来填充该属性。
例如,如果您想使用IMessageSummary.Envelope
,则需要MessageSummaryItems.Envelope
在您的Fetch()
请求中包含。
由于MessageSummaryItems
用[Flags]
属性标记,您可以像这样一起按位或枚举值:
MessageSummaryItems.BodyStructure | MessageSummaryItems.Envelope
并且将获取两条信息。
更新:
这是更接近 MailSystem.NET 的低效方式。
using (var client = new ImapClient ()) {
client.Connect ("imap.mail-server.com", 993, SecureSocketOptions.SslOnConnect);
client.Authenticate ("username", "password");
// if you don't care about modifying message flags or deleting
// messages, you can open the INBOX in read-only mode...
client.Inbox.Open (FolderAccess.ReadOnly);
// search for messages sent since a particular date
var uids = client.Inbox.Search (SearchQuery.SentAfter (date));
// using the uids of the matching messages, fetch the BODYSTRUCTUREs
// of each message so that we can figure out which MIME parts to
// download individually.
foreach (var uid in uids) {
var message = client.Inbox.GetMessage (uid);
foreach (var attachment in message.Attachments.OfType<MimePart> ()) {
using (var stream = File.Create (attachment.FileName))
attachment.ContentObject.DecodeTo (stream);
}
}
}
注意:如果您关心保存消息/rfc822 附件,请查看此 StackOverflow 答案:MailKit 保存附件