1. Follow the official guide to setup OAuth2
https://developers.google.com/gmail/api/guides
https://console.cloud.google.com/apis/credentials/consent
2. Follow the official quick start to make sure you can print the label list
https://github.com/googleworkspace/java-samples/blob/main/gmail/quickstart/src/main/java/GmailQuickstart.java
3. Update the GmailQuickstart.java to print unread Emails:
setQ("is:unread") is used to retrieve the unread Emails only.
To mark the Emails as read, need add GMAIL_MODIFY: private static final List<String> SCOPES = Arrays.asList(GmailScopes.GMAIL_READONLY, GmailScopes.GMAIL_MODIFY);
Also need to remove the folder "tokens" under the project folder so that you can see a prompt to force a re-consent or reauthorization flow.
// private static final String USER = "me";
List<Message> mesageList = service.users().messages().list(USER).setQ("is:unread").execute().getMessages();
if(mesageList==null) {
System.out.println("No new messages!");
return;
}
for(Message message:mesageList) {
String subject = "";
String from = "";
String date = "";
Message fullMessage = service.users().messages().get(USER, message.getId()).execute();
List<MessagePartHeader> headers = fullMessage.getPayload().getHeaders();
for (MessagePartHeader header : headers) {
switch (header.getName()) {
case "Subject":
subject = header.getValue();
break;
case "From":
from = header.getValue();
break;
case "Date":
date = header.getValue();
break;
}
}
System.out.println("Subject: " + subject);
System.out.println("From: " + from);
System.out.println("Date: " + date);
markAsRead(service,USER,message.getId());
System.out.println();
}
}
private static void markAsRead(Gmail service, String userId, String messageId) throws IOException {
ModifyMessageRequest mods = new ModifyMessageRequest().setRemoveLabelIds(Collections.singletonList("UNREAD"));
service.users().messages().modify(userId, messageId, mods).execute();
}
The full runnable source code is on
https://github.com/auspix/java-samples/blob/main/gmail/quickstart/src/main/java/GmailReader.java