Server
Question How does you delete a message from the mail server?
Derived from a unanswered question originally posed by Benjamin Alejandro Rodriguez Rengifo
Topics Java:API:JavaMail:IMAP4, Java:API:JavaMail:POP3
Author John Zukowski
Created 23-feb-00 Modified 25-jul-00
Answer
The basic process of deleting a message is to call Setflag () on the and set the Flags.Flag.DELETED Flag to True.
Message.setflag (Flags.Flag.DELETED, true);
Then, when you close the folder, deleted messages'll be removed.
Be sure to open the folder for Read/write access:
Folder.open (Folder.read_write);
The following program demonstrates listing the "all" and prompting for deletion:
Import java.io.*;
Import javax.mail.*;
Import javax.mail.internet.*;
public class Deletemessageexample {
public static void Main (String args[]) throws Exception {
String host = Args[0];
String username = args[1];
String password = args[2];
Get sessions
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");
Folder.open (Folder.read_write);
BufferedReader reader = new BufferedReader (
New InputStreamReader (system.in));
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 your 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 ();
}
}
You can also expunge () the Folder. However, the POP3 server from Sun does not support this operation.