Deleting email in Java Mail API

We already discussed the fundamentals of Java Mail API.

In the previous chapters we were discussed the way by which Java mail API uses SMTP to send emails with attachment and without attachment. Also we discussed the way by which Java Mail API is reading emails using POP as well as IMAP.In this chapter we are discussing how an email can be deleted from Gmail inbox from a Java application.

We are accessing Gmail mail server in our application.We are displaying the unread mails from inbox using IMAP as protocol. Then deleting the first unread email .When the program exits and if we open the inbox , then we can observe the result properly.

An email can be deleted from inbox by using

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

The predefined flags are defined in the inner class Flags.Flag and are listed below:

  • Flags.Flag.ANSWERED
  • Flags.Flag.DELETED
  • Flags.Flag.DRAFT
  • Flags.Flag.FLAGGED
  • Flags.Flag.RECENT
  • Flags.Flag.SEEN
  • Flags.Flag.USER

For receiving or sending the email using JavaMail API, you need to load the two jar files:

  • mail.jar
  • activation.jar

Steps for deleting the email using JavaMail API
There are total 5 steps for deleting the email. They are:

  1. Get the session object
  2. create the store object and connect to the current host
  3. create the folder object and open it
  4. Get the message to delete
  5. delete the message using setFlag method

Example of deleting email using JavaMail API-
Now let us see the Java application. The following class needs to put as a class in a dynamic web project. If we need to access mails from J2SE application , then we can download Java Mail API from here.Extract the zip file and include the jar files in the project path.

import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
public class DeleteMailSample {
    Properties properties = null;
    private Session session = null;
    private Store store = null;
    private Folder inbox = null;
    private Message messages[];
    private String userName = "*******";// provide user name
    private String password = "********";// provide password
    public DeleteMailSample() {

    public void getMails() {
        if (null != messages && messages.length > 0) {
            System.out.println("trying to delete  first mail...");

   public void getConnection() {
        properties = new Properties();
        properties.setProperty("", "");
        properties.setProperty("mail.port", "995");
        properties.setProperty("mail.transport.protocol", "imaps");
        session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(userName, password);
        try {
            store = session.getStore("imaps");
            inbox = store.getFolder("INBOX");
        } catch (NoSuchProviderException e) {
        } catch (MessagingException e) {

     public void readMails() {
        try {
            if (null != inbox) {
                messages = FlagTerm(new Flags(Flag.SEEN),false));
                System.out.println("Number of mails = " + messages.length);
                for (int i = 0; i < messages.length; i++) {
                    Message message = messages[i];
                    Address[] from = message.getFrom();
                    System.out.println("Date : " + message.getSentDate());
                    System.out.println("From : " + from[0]);
                    System.out.println("Subject: " + message.getSubject());
                    System.out.println("Content :");
        } catch (MessagingException e) {

    public void closeSession() {
        if (null != inbox && null != store) {
            try {
            } catch (MessagingException e) {
    public void deleteMessage(Message message) {
        try {
            message.setFlag(Flags.Flag.DELETED, true);
            System.out.println("deleted mail");
        } catch (MessagingException e) {
    public void processMessageBody(Message message) {
        try {
            Object content = message.getContent();
           // check for string
            // then check for multipart
            if (content instanceof String) {
            } else if (content instanceof Multipart) {
                Multipart multiPart = (Multipart) content;
            } else if (content instanceof InputStream) {
                InputStream inStream = (InputStream) content;
                int ch;
                while ((ch = != -1) {
        } catch (IOException e) {
        } catch (MessagingException e) {

    public void procesMultiPart(Multipart content) {
        try {
            int multiPartCount = content.getCount();
            for (int i = 0; i < multiPartCount; i++) {
                BodyPart bodyPart = content.getBodyPart(i);
                Object o;
                o = bodyPart.getContent();
                if (o instanceof String) {
                } else if (o instanceof Multipart) {
                    procesMultiPart((Multipart) o);
        } catch (IOException e) {
        } catch (MessagingException e) {
    public static void main(String[] args) {
        DeleteMailSample sample = new DeleteMailSample();

Provide username and password for gmail account. Then compile and run the code. Assume our inbox has 1 unread mail as of now. So the number of mails will be displayed as 1.Then it will display the individual mails one by one. At last it will delete the first mail in inbox. This can be verified by logging in to gmail account from any client or using browser.

Inbox before running this application-

Deleting email in Java Mail API

Now set up classpath and compile java file as follows-

Deleting email in Java

Now after run this application please see Inbox Mail is deleted-

Deleting email in Java Mail

<<Previous <<   || Index ||   >>Next >>