我正在尝试学习如何使用 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;
最佳答案
我不完全清楚你想要完成什么,但如果你只想下载邮件附件(而不是下载整封邮件)并将这些附件保存到文件系统,你可以按照以下方法完成:
var messages = client.Inbox.Fetch (0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId);
int unnamed = 0;
foreach (var message in messages) {
var multipart = message.Body as BodyPartMultipart;
var basic = message.Body as BodyPartBasic;
if (multipart != null) {
foreach (var attachment in multipart.BodyParts.OfType<BodyPartBasic> ().Where (x => x.IsAttachment)) {
var mime = (MimePart) client.Inbox.GetBodyPart (message.UniqueId.Value, attachment);
var fileName = mime.FileName;
if (string.IsNullOrEmpty (fileName))
fileName = string.Format ("unnamed-{0}", ++unnamed);
using (var stream = File.Create (fileName))
mime.ContentObject.DecodeTo (stream);
}
} else if (basic != null && basic.IsAttachment) {
var mime = (MimePart) client.Inbox.GetBodyPart (message.UniqueId.Value, basic);
var fileName = mime.FileName;
if (string.IsNullOrEmpty (fileName))
fileName = string.Format ("unnamed-{0}", ++unnamed);
using (var stream = File.Create (fileName))
mime.ContentObject.DecodeTo (stream);
}
}
关于c# - 使用 MailKit 库保存附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24455519/