Use IMAP for that. Email attachments are downloaded along with the email message. This means, that invoking Imap.GetMessageByUID method is going to download entire email message, including all attachments.
Mail.dll parses mail message and exposes attachments as well-known .NET collections.
There are 4 collections that may contain attachments:
- IMail.Attachments – contains all attachments (includes Visuals, NonVisuals and Alternatives).
- IMail.Visuals – visual elements, files that should be displayed to the user, for example images embedded in an HTML email.
- IMail.NonVisuals – non visual elements - "real" attachments.
- IMail.Alternatives – alternative content representations, for example icalendar appointment.
Here's the code that downloads unseen email message, iterates attachments and saves them to disk:
using(Imap imap = new Imap())
{
imap.Connect("imap.example.com"); // or ConnectSSL for SSL
imap.UseBestLogin("user", "password");
imap.SelectInbox();
List<long> uids = imap.Search(Flag.Unseen);
foreach (long uid in uids)
{
var eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(email.Subject);
foreach (MimeData mime in email.Attachments)
{
mime.Save(@"c:\" + mime.SafeFileName);
}
}
imap.Close();
}
also to open the attachments in browser
Use Process.Start for that.
Reference:
https://www.limilabs.com/blog/save-all-attachments-to-disk-using-imap