Deleting messages example
This Example shows you how delete a message. If you want to delete any message then set the message flag delete. There are different types of flags, some system-defined and some user-defined.
* Flags.Flag.ANSWERED* Flags.Flag.DELETED* Flags.Flag.DRAFT* Flags.Flag.FLAGGED* Flags.Flag.RECENT* Flags.Flag.SEEN* Flags.Flag.USERTo delete messages, you set the message's DELETED flag:message.setFlag(Flags.Flag.DELETED, true);Open up the folder in READ_WRITE mode first though:folder.open(Folder.READ_WRITE);Then, when you are done processing all messages, close the folder, passing in a true value to expunge the deleted messages.
folder.close(true);
DeleteMail.java
import com.sun.mail.imap.protocol.FLAGS; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.InternetAddress; public class DeleteMail { public static void main(String args[]) throws Exception { Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties); Store store = session.getStore("pop3"); store.connect("192.168.10.205", "test", "test"); Folder folder = store.getFolder("inbox"); if (!folder.exists()) { System.out.println("inbox not found"); System.exit(0); } folder.open(Folder.READ_WRITE); Message[] msg = folder.getMessages(); //System.out.println((messages.length+1)+" message found"); for (int i = 0; i < msg.length; i++) { System.out.println("--------- " + (i + 1) + "------------"); String from = InternetAddress.toString(msg[i].getFrom()); if (from != null) { System.out.println("From: " + from); } String replyTo = InternetAddress.toString( msg[i].getReplyTo()); if (replyTo != null) { System.out.println("Reply-to: " + replyTo); } String to = InternetAddress.toString( msg[i].getRecipients(Message.RecipientType.TO)); if (to != null) { System.out.println("To: " + to); } String subject = msg[i].getSubject(); if (subject != null) { System.out.println("Subject: " + subject); } Date sent = msg[i].getSentDate(); if (sent != null) { System.out.println("Sent: " + sent); } System.out.println("Message : "); System.out.println(msg[i].getContent()); } System.out.println("Enter message no to delete :"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String no = br.readLine(); msg[Integer.parseInt(no) - 1].setFlag(FLAGS.Flag.DELETED, true); System.out.println("Msg Delete ....."); folder.close(true); store.close(); } }
Output:
--------- 1------------ |