Search code examples
jakarta-mailgmail-imap

Java Mail Api, delete mails from gmail


For testing reasons, I want an email account to be empty every day, I have this code but isn't deleting the emails.

public class EmailService {

  private String HOST = "imap.gmail.com";
  private String USERNAME = "[email protected]";
  private String PASSWORD = "pass";
  private Properties properties;
  private Store store;
  private Folder inbox;

  public EmailService() throws MessagingException {
    this.properties = new Properties();
    this.properties.put("mail.imap.host", HOST);
    this.properties.put("mail.imap.port", "993");
    this.properties.put("mail.imap.starttls.enable", "true");
  }

  public void openEmailSession() throws MessagingException, InterruptedException {
    Session emailSession = Session.getInstance(this.properties);
    emailSession.setDebug(true);
    this.store = emailSession.getStore("imaps");
    this.store.connect(HOST, USERNAME, PASSWORD);

    this.inbox = this.store.getFolder("INBOX");
    this.inbox.open(Folder.READ_WRITE);
  }

  public void closeEmailSession() throws MessagingException, IOException {
    this.inbox.close(true);
    this.store.close();
  }

  public Message[] getUserMessages() throws MessagingException, IOException {
    Message[] messages = this.inbox.getMessages();
    return messages;
  }

  public void cleanInbox() throws IOException, MessagingException {
    Message[] messages = this.getUserMessages();
    for (Message message :messages) {
      message.setFlag(Flags.Flag.DELETED, true);
    }
  }
}

When I execute:

emailService.openEmailSession();
emailService.cleanInbox();
emailService.closeEmailSession();

The emails disappear from inbox, but then I click on All Mail and the emails still there and the trash is empty. I don't understand what is happening.

On the gmail settings in "Forwarding and POP/IMAP" I already tried autoexpunge on/off and the three options in "When a message is marked as deleted and expunged from the last visible IMAP folder"

But nothing changes... What I'm missing?

Edit: Debug output for [Gmail]/All mail

DEBUG: setDebug: JavaMail version 1.5.6
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: trying to connect to host "imap.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from 46.25.184.193 f20mb151859057edc
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN AUTH=OAUTHBEARER AUTH=XOAUTH
A0 OK Thats all she wrote! f20mb151859057edc
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: PLAIN-CLIENTTOKEN
DEBUG IMAPS: AUTH: OAUTHBEARER
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: protocolConnect login, host=imap.gmail.com, [email protected], password=<non-null>
DEBUG IMAPS: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAPS: AUTHENTICATE PLAIN command result: A1 OK [email protected] authenticated (Success)
A2 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS LITERAL- APPENDLIMIT=35651584
A2 OK Success
DEBUG IMAPS: connection available -- size: 1
A3 SELECT "[Gmail]/All Mail"
* FLAGS (\Answered \Flagged \Draft \Deleted \Seen $NotPhishing $Phishing)
* OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted \Seen $NotPhishing $Phishing \*)] Flags permitted.
* OK [UIDVALIDITY 11] UIDs valid.
* 10 EXISTS
* 0 RECENT
* OK [UIDNEXT 3903] Predicted next UID.
* OK [HIGHESTMODSEQ 101809]
A3 OK [READ-WRITE] [Gmail]/All Mail selected. (Success)
A4 STORE 1 +FLAGS (\Deleted)
* 1 FETCH (FLAGS (\Seen \Deleted))
A4 OK Success
A5 STORE 2 +FLAGS (\Deleted)
* 2 FETCH (FLAGS (\Deleted))
A5 OK Success
A6 STORE 3 +FLAGS (\Deleted)
* 3 FETCH (FLAGS (\Seen \Deleted))
A6 OK Success
A13 OK Success
A14 CLOSE
A14 OK Returned to authenticated state. (Success)
DEBUG IMAPS: added an Authenticated connection -- size: 1
A15 LOGOUT
* BYE LOGOUT Requested
A15 OK 73 good day (Success)
DEBUG IMAPS: IMAPStore connection dead
DEBUG IMAPS: IMAPStore cleanup, force false
DEBUG IMAPS: IMAPStore cleanup done

Solution

  • I found an alternative solution, is not the best for my purpose (jenkins integration) but it works for now.

    Is a really simple function in google script, you can select your email and schedule the function as you want.

    https://www.google.com/script/start/

    function cleanInbox() {
      var threads = GmailApp.search('label:inbox');
      for (var i = 0; i < threads.length; i++) {
        threads[i].moveToTrash();
      }
    }