I am trying to learn how to use the MailKit library, but I am trying to get attachments. While my code opens the mailbox, look at each message and save the data, such as sender, subject, body, date, etc., but I can not deal with attachments.
I tried to use other people's solutions found here on github and other sites, but I still donβt understand what they are doing in my code, and when I get closer to working with the solution, it causes more errors. I get stress and delete all the code. I do not want to seem lazy, but I would like someone to explain how I can achieve this. I am mainly trying to create an email client for a web forms application.
Below is my code, as you can see that I'm pretty clueless :)
// 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 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;
Supernatix
source share