Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Delete Individual Emails from POP3 Mailbox

Demonstrates how to delete individual emails from a POP3 mailbox.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.EmailBundle;
import com.chilkatsoft.chilkat2.MailMan;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // The mailman object is used for receiving (POP3)
        // and sending (SMTP) email.
        MailMan mailman = new MailMan();

        // Set the POP3 server's hostname
        mailman.setMailHost("pop.example.com");

        // Set the POP3 login/password.
        mailman.setPopUsername("myLogin");
        mailman.setPopPassword("myPassword");

        // Set the ImmediateDelete property = false
        // When the DeleteEmail method is called, the POP3 session
        // will remain open and the emails will be deleted all at once
        // when the session closes.
        mailman.setImmediateDelete(false);

        // Download email headers.
        EmailBundle bundle = new EmailBundle();
        boolean keepOnServer = true;
        boolean headersOnly = true;
        int numBodyLines = 1;
        try {
            mailman.fetchAll(keepOnServer, headersOnly, numBodyLines, bundle);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Email email = new Email();
        int i = 0;
        while (i < bundle.getMessageCount()) {
            bundle.emailAt(i, email);

            System.out.println("From: " + email.getFrom());
            System.out.println("Subject: " + email.getSubject());

            // If you decide the email is to be deleted, call DeleteEmail.
            // This marks the email for deletion on the POP3 server.
            try {
                mailman.deleteEmail(email);
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            i = i + 1;
        }

        // Make sure the POP3 session is ended to finalize the deletes.
        try {
            mailman.pop3EndSession();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Success!");
    }
}