JavaMail Projects

JavaMail Project 1

Deleting Message or Mail Using Java Mail API
Previous Home Next

If you want to Delete a Message or Mail for Using Java Mail API. Then you using a method call for deleting messages call setFlag() on set the message and set the Flags.Flag.DELETED flag is true.

message.setFlag(Flags.Flag.DELETED, true);

When you close the folder, deleted message will be removed. then be sure the open the folder for read/write access;
package R4R;
import javax.mail.*;
import javax.mail.internet.*;
public class deletemail{
  public static void main (String args[]) throws Exception {
    String host = args[0];
    String username = args[1];
    String password = args[2];
    // Get session
    Session session = Session.getInstance(
      System.getProperties(), null);
    // Get the store
    Store store = session.getStore("pop3");
    store.connect(host, username, password);
    // Get folder


Folder folder = store.getFolder("INBOX");; BufferedReader reader = new BufferedReader ( new InputStreamReader(; // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; i<n; i++) { System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); System.out.println("Do you want to delete message? [YES to delete]"); String line = reader.readLine(); // Mark as deleted if appropriate if ("YES".equals(line)) { message[i].setFlag(Flags.Flag.DELETED, true); } } // Close connection folder.close(true); store.close(); } }
Previous Home Next