我正在尝试学习如何使用 MailKit 库,但我正在努力检索附件。到目前为止,我的代码将打开一个邮箱,浏览每条消息并存储发件人、主题、正文、日期等数据,但我无法处理附件。
我曾尝试使用在此处、github 和其他网站上找到的其他人的解决方案,但我仍然不明白他们在他们的代码中做了什么,当我接近让解决方案正常工作时,它会导致更多错误,所以我感到压力并删除所有代码。我并不是要显得懒惰,但如果有人能解释我如何做到这一点,我会很高兴。我基本上是在尝试为 Web 表单应用程序构建邮件客户端。
下面是我的代码,所以你可以看到我相当无能:)
// Open the Inbox folder
client.Inbox.Open(FolderAccess.ReadOnly, cancel.Token);
//get the full summary information to retrieve all details
var summary = client.Inbox.Fetch(0, -1, MessageSummaryItems.Full, cancel.Token);
foreach (var msg in summary)
{
//this code originally downloaded just the text from the body
var text = msg.Body as BodyPartText;
//but I tried altering it so that it will get attachments here also
var attachments = msg.Body as BodyPartBasic;
if (text == null)
{
var multipart = msg.Body as BodyPartMultipart;
if (multipart != null)
{
text = multipart.BodyParts.OfType<BodyPartText>().FirstOrDefault();
}
}
if (text == null)
continue;
//I hoped this would get the messages where the content dispositon was not null
//and let me do something like save the attachments somewhere but instead it throws exceptions
//about the object reference not set to an instance of the object so it's very wrong
if (attachments.ContentDisposition != null && attachments.ContentDisposition.IsAttachment)
{
//I tried to do the same as I did with the text here and grab the body part....... but no
var attachedpart = client.Inbox.GetBodyPart(msg.Index, attachments, cancel.Token);
}
else
{
//there is no plan b :(
}
// this will download *just* the text
var part = client.Inbox.GetBodyPart(msg.Index, text, cancel.Token);
//cast main body text to Text Part
TextPart _body = (TextPart)part;