Reputation: 626
I have using a console app for downloading document from the mail using IMAP Service. I use "S22.Imap" assembly in application for the IMAP. I got the all mails contains attached files in IEnumerable. How could I download these Files?
using (ImapClient client = new ImapClient(hostname, 993, username, password, AuthMethod.Login, true))
{
IEnumerable<uint> uids = client.Search(SearchCondition.Subject("Attachments"));
IEnumerable<MailMessage> messages = client.GetMessages(uids,
(Bodypart part) =>
{
if (part.Disposition.Type == ContentDispositionType.Attachment)
{
if (part.Type == ContentType.Application &&
part.Subtype == "VND.MS-EXCEL")
{
return true;
}
else
{
return false;
}
}
return true;
}
);
}
I would appreciate it, if you give a solution
Upvotes: 5
Views: 18483
Reputation: 5734
This code will store attachment file inside c drive in Download folder .
foreach (var msg in messages)
{
foreach (var attachment in msg.Attachments)
{
byte[] allBytes = new byte[attachment.ContentStream.Length];
int bytesRead = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length);
string destinationFile = @"C:\Download\" + attachment.Name;
BinaryWriter writer = new BinaryWriter(new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None));
writer.Write(allBytes);
writer.Close();
}
}
Hope help to someone
Upvotes: 0
Reputation: 2430
The attachments type has a property on it called ContentStream
you can see this on the msdn documentation: https://msdn.microsoft.com/en-us/library/system.net.mail.attachment(v=vs.110).aspx.
Using that you can use something like this to then save the file:
using (var fileStream = File.Create("C:\\Folder"))
{
part.ContentStream.Seek(0, SeekOrigin.Begin);
part.ContentStream.CopyTo(fileStream);
}
Edit:
So after GetMessages
is done you could do:
foreach(var msg in messages)
{
foreach (var attachment in msg.Attachments)
{
using (var fileStream = File.Create("C:\\Folder"))
{
attachment.ContentStream.Seek(0, SeekOrigin.Begin);
attachment.ContentStream.CopyTo(fileStream);
}
}
}
Upvotes: 10
Reputation: 147
messages.Attachments.Download();
messages.Attachments.Save("location", fileSaveName)
this way you can download attachment in email using IMAP
Upvotes: 0
Reputation: 381
I think the best source will be the documentation http://smiley22.github.io/S22.Imap/Documentation/
Upvotes: 1