Categories: JavaMail

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.

Deleting email in Java Mail API

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.

DeleteMailSample.java

import java.io.IOException;
import java.io.InputStream;
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;
import javax.mail.search.FlagTerm;
public class DeleteMailSample {
    Properties properties = null;
    private Session session = null;
    private Store store = null;
    private Folder inbox = null;
    private Message messages[];
    private String userName = "*******@gmail.com";// provide user name
    private String password = "********";// provide password
    public DeleteMailSample() {
    }

    public void getMails() {
        getConnection();
        readMails();
        if (null != messages && messages.length > 0) {
            System.out.println("trying to delete  first mail...");
            deleteMessage(messages[0]);
            closeSession();
        }
    }

   public void getConnection() {
        properties = new Properties();
        properties.setProperty("mail.host", "imap.gmail.com");
        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");
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

     public void readMails() {
        try {
            if (null != inbox) {
                messages = inbox.search(new 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("-------------------------------");
                    System.out.println("Date : " + message.getSentDate());
                    System.out.println("From : " + from[0]);
                    System.out.println("Subject: " + message.getSubject());
                    System.out.println("Content :");
                    processMessageBody(message);
                    System.out.println("--------------------------------");
                }
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

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

    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) {
                    System.out.println(o);
                } else if (o instanceof Multipart) {
                    procesMultiPart((Multipart) o);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        DeleteMailSample sample = new DeleteMailSample();
        sample.getMails();
    }
}

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-

Now set up classpath and compile java file as follows-

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

 

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

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago