Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Email on Server using javax.mail

Tags:

java

email

imap

I am receiving emails from the server using the IMAP protocol like it is described here. This is working very fine and I can store the emails and attachments on the disk.

Question: Do I have the possibility to delete files from the Server, so that they are no longer available, when a client tries to receive all emails? If so, please tell me how.

like image 684
Markus Lausberg Avatar asked Sep 23 '09 08:09

Markus Lausberg


People also ask

How do I delete emails from server?

In the Edit Account box click on the Options tab. Under the Server options section: Clear the check box Leave a copy of each message on the server. If you would like to leave messages on the server, check the box Delete messages from the server after and specify the number of days.

How do I delete emails from IMAP server?

IMAP accounts provide several options to delete messages that aren't available in POP accounts. Tools -> Account Settings -> Account Name -> Server Settings -> "When I delete a message" has choices for "Move it to the Trash folder", "Mark it as deleted" and "Remove it immediately".

How do you delete a message in Java?

Iterate through the messages and type "Y" or "y" if you want to delete the message by invoking the method setFlag(Flags. Flag. DELETED, true) on the Message object.

What is the use of javax mail?

The javax. mail. internet package defines classes that are specific to mail systems based on internet standards such as MIME, SMTP, POP3, and IMAP.


1 Answers

You should be able to do this via the standard APIs.

First you need to get a reference to the Message (or messages) you want to delete - if you're successfully reading them then you're already able to do this. Now, there's no explicit delete() operation, but you can mark a message as deleted like so:

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

This will mark the message as deleted (which is typically what a delete operation will do in a desktop IMAP client). In order to force the deleted messages to be expunged, when you're finished with the Folder(s) in which they reside, call

folder.close(true); 

where the true flag instructs the server to expunge all deleted messages.

And voila! The client should no longer see these messages when he connects to the server with any IMAP client.

EDIT:

Don't forget to open the folder in READ_WRITE mode otherwise the messages will not actually be deleted from the server.

folder.open(Folder.READ_WRITE); 

See: http://java.sun.com/developer/onlineTraining/JavaMail/contents.html#JavaMailDeleting

like image 170
Andrzej Doyle Avatar answered Oct 04 '22 03:10

Andrzej Doyle