Deleting email in 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:

Get the session object

create the store object and connect to the current host

create the folder object and open it

Get the message to delete

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.

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.