We are explaining here an example of deleting emails using JavaMail API.
Steps of deleting email using JavaMail API:
-
1. Get a session instance from getDefaultInstance() or getInstance() method of Session class.
2. Create the store object (POP3) and connect to the pop store.
3. Create the folder object by calling getFolder() method on store object and open it in mailbox.
4. Get the messages from the folder object.
5. Iterate the emails and get all information like to, from, subject, content etc.
6. Retrieve the email message to be deleted.
7. Call the setFlag(Flags.Flag.DELETED, true) method on this message object.
8. Set expunge to true and close the folder.
Close store object.
Example:
DeleteEmail.java
import java.io.*; import java.util.*; import javax.mail.*; /** * This class is used to delete email. * @author w3schools */ public class DeleteEmail { public static void deleteEmail(String pop3Host, String storeType, String user, String password){ Properties props = new Properties(); props.put("mail.pop3.host", pop3Host); Session session = Session.getInstance(props); try { Store store = session.getStore(storeType); store.connect(pop3Host, user, password); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); Message[] messages = folder.getMessages(); System.out.println("Total Message - " + messages.length); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); for (int i = 0; i < messages.length; i++) { Message emailMessage = messages[i]; System.out.println(); System.out.println("Email " + (i+1) + " -"); System.out.println("Subject - " + emailMessage.getSubject()); System.out.println("From - " + emailMessage.getFrom()[0]); } System.out.print("Enter email number " + "which you want to delete: "); String emailNo = reader.readLine(); messages[Integer.parseInt(emailNo) - 1]. setFlag(Flags.Flag.DELETED, true); folder.close(true); store.close(); System.out.println("Email" + " deleted successfully."); } catch (Exception e) { e.printStackTrace(); System.err.println("Error in deleting email."); } } public static void main(String[] args) { String pop3Host = "pop.gmail.com"; String mailStoreType = "pop3s"; final String userName = "[email protected]"; final String password = "****"; //call deleteEmail deleteEmail(pop3Host, mailStoreType, userName, password); } } |
Output:
DEBUG POP3: server doesn't support TOP, disabling it Total Message - 260 Email 1 - Subject - Derek Banas added you back on Google+ From - Google+ <[email protected]> Email 2 - Subject - w3schools, find your friends on Twitter! From - Twitter <[email protected]> Enter email number which you want to delete: 2 Email deleted successfully. |
Download this example.
Next Topic: Quartz scheduler Tutorial with example.
Previous Topic: Forwarding emails with example.