In this post, I will guide you how to write Java code to delete emails on a mail server programmatically.

To send emails with Java, you need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

To delete e-mail messages which are stored on mail server using JavaMail API, it requires following the steps below:

-          Open the inbox folder in READ_WRITE mode.

-          Retrieves messages from inbox folder (For more details, see the article Receive e-mail messages from a POP3-IMAP server).

-          Iterate through the received messages, if one needs to be delete, mark it as deleted by invoking the method setFlag(Flags.Flag.DELETED, true)on the Messageobject. For example: 

if (message.getSubject().contains("Promo")) {
	message.setFlag(Flags.Flag.DELETED, true);
}

 

-          The messages marked DELETED are not actually deleted, until we call the expunge() method on the Folder object, or close the folder with expunge set to true. For example:

boolean expunge = true;
folder.close(expunge);

      or:

folder.expunge();
folder.close(false);

 

 The following sample program demonstrates how to conditionally delete e-mail messages with subject field contains the word “Newsletter”:

package net.codejava.mail;

import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

/**
 * This program demonstrates how to remove e-mail messages on a mail server
 * using JavaMail API.
 * @author www.codejava.net
 *
 */
public class EmailMessageRemover {

	/**
	 * Deletes all e-mail messages whose subject field contain
	 * a string specified by 'subjectToDelete'
	 * @param host
	 * @param port
	 * @param userName
	 * @param password
	 * @param subjectToDelete delete if the message's subject contains this value.
	 */
	public void deleteMessages(String host, String port,
			String userName, String password, String subjectToDelete) {
		Properties properties = new Properties();

		// server setting
		properties.put("mail.imap.host", host);
		properties.put("mail.imap.port", port);

		// SSL setting
		properties.setProperty("mail.imap.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		properties.setProperty("mail.imap.socketFactory.fallback", "false");
		properties.setProperty("mail.imap.socketFactory.port",
				String.valueOf(port));

		Session session = Session.getDefaultInstance(properties);

		try {
			// connects to the message store
			Store store = session.getStore("imap");
			store.connect(userName, password);

			// opens the inbox folder
			Folder folderInbox = store.getFolder("INBOX");
			folderInbox.open(Folder.READ_WRITE);

			// fetches new messages from server
			Message[] arrayMessages = folderInbox.getMessages();

			for (int i = 0; i < arrayMessages.length; i++) {
				Message message = arrayMessages[i];
				String subject = message.getSubject();
				if (subject.contains(subjectToDelete)) {
					message.setFlag(Flags.Flag.DELETED, true);
					System.out.println("Marked DELETE for message: " + subject);
				}

			}

			// expunges the folder to remove messages which are marked deleted
			boolean expunge = true;
			folderInbox.close(expunge);

			// another way:
			//folderInbox.expunge();
			//folderInbox.close(false);

			// disconnect
			store.close();
		} catch (NoSuchProviderException ex) {
			System.out.println("No provider.");
			ex.printStackTrace();
		} catch (MessagingException ex) {
			System.out.println("Could not connect to the message store.");
			ex.printStackTrace();
		}
	}

	/**
	 * Runs this program to delete e-mail messages on a Gmail account
	 * via IMAP protocol.
	 */
	public static void main(String[] args) {
		String host = "imap.gmail.com";
		String port = "993";
		String userName = "your_email";
		String password = "your_password";
		EmailMessageRemover remover = new EmailMessageRemover();

		// try to delete all messages contain this string its Subject field
		String subjectToDelete = "Newsletter";
		remover.deleteMessages(host, port, userName, password, subjectToDelete);

	}
} 

The program above is tested with a Gmail account using IMAP protocol. Change value of userNameand password to match with your account.

 

Other JavaMail Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (EmailMessageRemover.java)EmailMessageRemover.java[Sample program for deleting e-mail messages]2 kB

Add comment

   


Comments 

#4huyquoc2015-04-18 04:15
so , if i deleted mail without subject, what would happen?
all this mails will be delete, right?
please help, thanks.
Quote
#3rajesh2015-01-21 23:35
thanks. helped and saved my time.
Quote
#2Nam2014-04-10 20:31
Hi Navi, nothing happens ? or is there any exceptions/errors?
Quote
#1Navi2014-04-07 08:28
I have tried,but its not deleting from server.
Quote