简体   繁体   中英

How to download multiple attachments per message with MailKit?

I've looked at a lot of the other questions on stackoverflow about this, but I'm still confused.

I want to download the attachments of emails- I was successfully able to do this, but only if the email had ONE attachment; when an email has more than one attachment, it stops working.

How do I download multiple attachments per email?

Also, is there a way to determine the file extension when downloading? Currently, for example, if there is a pdf attachment, the file downloads, but with no .pdf, so windows doesn't know the file type.

The code below is from here: MailKit save Attachments . I've been basing my code off of that.

foreach (var attachment in message.Attachments)
{
    using (var stream = File.Create ("fileName"))
    {
        if (attachment is MessagePart)
        {
            var part = (MessagePart) attachment;
            part.Message.WriteTo (stream);
        }
        else
        {
            var part = (MimePart) attachment;
            part.ContentObject.DecodeTo (stream);
        }
    }
}

Please help! Thanks!

The code you pasted will already save all attachments.

Look at the raw message source. Does each "attachment" that you consider to be an attachment have a header Content-Disposition: attachment ? If not, that's the problem you are hitting.

You can instead use message.BodyParts and apply your own logic to determine if the part is what you would consider to be an "attachment".

Also, is there a way to determine the file extension when downloading? Currently, for example, if there is a pdf attachment, the file downloads, but with no .pdf, so windows doesn't know the file type.

Yes. You can check the file extension on the FileName property on MimePart objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM