Always getting the whole message from a mail server is not always efficient, especially when working with many messages. The IMAP protocol allows for the download of specific message parts without downloading the whole message and with the Imap component this operation is easily accomplished.
To quickly and easily save all attachments to disk from all the messages.
- Add the Imap component to a new form.
- Import the namespace of the component you would like to use using "Using" (C#) or "Imports" (VB.NET). Place the following code at the top of your file.
C#
Copy Codeusing Dart.PowerTCP.Mail;Visual Basic
Copy CodeImports Dart.PowerTCP.Mail - Add a button to the form.
- Login to the server.
C#
Copy Code// Login to the IMAP server. imap1.Login("mail.myserver.com", "test", "pass");
Visual Basic
Copy Code' Login to the IMAP server. Imap1.Login("mail.myserver.com", "test", "pass")
- At this point, if Imap.AutoList is True (by default), a List command is sent to the server immediately after the login occurs, returning all the mailboxes and the number of messages contained in each mailbox. The default current mailbox is "INBOX" as that is the most commonly used mailbox on mail servers. To discover all the attachments in "INBOX" get all the message body structures.
C#
Copy Codeimap1.CurrentMailbox.Get(imap1.CurrentMailbox.Messages[0], imap1.CurrentMailbox.Messages[imap1.CurrentMailbox.Messages.Count - 1], ImapMessageSections.Text);Visual Basic
Copy CodeImap1.CurrentMailbox.Get(Imap1.CurrentMailbox.Messages(0), _ Imap1.CurrentMailbox.Messages(Imap1.CurrentMailbox.Messages.Count - 1), _ ImapMessageSections.Text) - The retrieved messages are represented as ImapMessage objects. To access each message, either index into the MailBox.Messages collection, or access each message using For...Each. Iterate through all the messages looking for attachments. If attachments are found then save them all to disk.
C#
Copy CodeAttachmentStream Attach; foreach(ImapMessage msg in imap1.CurrentMailbox.Messages) { //Iterate through all the messages looking for attachments if (msg.Message.Attachments.Count > 0) { //When a message is found to contain attachments, iterate //through the attachments and save them to disk for (int i=0; i < msg.Message.Attachments.Count ; i++) { Attach = msg.Message.Attachments[i]; msg.GetPart(Attach); Attach.Save("c:\\temp\\" + Attach.FileName, true); } } } imap1.Logout();
Visual Basic
Copy CodeDim Attach As AttachmentStream Dim i as Integer Dim msg as ImapMessage For Each Msg In imap1.CurrentMailbox.Messages 'Iterate through all the messages looking for attachments If msg.Message.Attachments.Count > 0 Then 'When a message is found to contain attachments, iterate 'through the attachments and save them to disk For i = 0 To msg.Message.Attachments.Count - 1 Attach = msg.Message.Attachments(i) msg.GetPart(Attach) Attach.Save("c:\temp\" + Attach.FileName, True) Next End If Next Imap1.Logout()