Deleting inbox mails from your code using JavaMailAPI

In my previous blog, I posted how after a little bit of research on Google, I was able to access to my Gmail account. Finally I was able to delete my mail too . 🙂

Now as I connected to Gmail in my previous post, I connect to my account.

Then, I connect to the store and specify the folder which we want to access.

Store store=session.getStore("imaps");
store.connect("",username, password);
Folder inbox = store.getFolder("Inbox");
Message inbox_message[]=inbox.getMessages();

Now , the list inbox_messages[] contain all my messages. If you want to get rid of all your unnecessary mails then please go ahead and delete them entirely. But I wanted too delete them for a specific date. So my code was like :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2013-11-17");

Deleting the mails in Gmail inbox is setting the flag to deleted.

for (Message msg : inbox_message) {
if (msg.getReceivedDate().equals(date1))
msg.setFlag(Flags.Flag.DELETED, true);
else {
System.out.println("No messages for the respective date");

Now check out the Gmail inbox. The mails for the above date should have been moved to Trash folder.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s