13

How do I mark mail as read using Gmail API?

I got the thread of email

Thread thread = service.users().threads().get(userId, message.getThreadId()).execute();

but it does not have method markRead like gmail API site says it should.

mason
  • 31,774
  • 10
  • 77
  • 121
Kun Dark
  • 141
  • 1
  • 2
  • 6
  • Where does Gmail API site say it has "method markRead"? Are you sure you're not confusing the Gmail API with the Google Apps Scripts interface? Gmail API: https://developers.google.com/gmail/api/v1/reference/users/threads/modify Apps Script: https://developers.google.com/apps-script/reference/gmail/gmail-thread – Eric D Oct 23 '14 at 23:33

7 Answers7

15

use either threads.modify() or messages.modify() (depending on scope of what you want to do) and removeLabelId of "UNREAD".

https://developers.google.com/gmail/api/v1/reference/users/threads/modify

Eric D
  • 6,901
  • 1
  • 15
  • 26
10

In nodejs example:

var google = require('googleapis');
var gmail = google.gmail('v1');
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
oauth2Client.credentials = JSON.parse(token);
google.options({ auth: oauth2Client }); // set auth as a global default

gmail.users.messages.modify({
        'userId':'me',
        'id':emailId,
        'resource': {
            'addLabelIds':[],
            'removeLabelIds': ['UNREAD']
        }
    }, function(err) {
        if (err) {
            error('Failed to mark email as read! Error: '+err);
            return;
        }
        log('Successfully marked email as read', emailId);
    });
kohane15
  • 809
  • 12
  • 16
Alex Egli
  • 1,884
  • 2
  • 24
  • 43
5

As I arrived here in search for this answer in C# here is the answer from my experience:

var gs = new GmailService(
                new BaseClientService.Initializer()
                {
                    ApplicationName = gmailApplicationName,
                    HttpClientInitializer = credential
                }
            );
var markAsReadRequest = new ModifyThreadRequest {RemoveLabelIds = new[] {"UNREAD"}};
                            await gs.Users.Threads.Modify(markAsReadRequest, "me", unreadMessage.ThreadId)
                                    .ExecuteAsync();
Ruli
  • 2,592
  • 12
  • 30
  • 40
The Senator
  • 5,181
  • 2
  • 34
  • 49
2

If anyone else stumbles upon this using the Golang API. Here is how you can do it:

msg, err := gmail.Users.Messages.Modify("me", msg.Id, &gmail.ModifyMessageRequest{
   RemoveLabelIds: []string{"UNREAD"},
}).Do()
Ruli
  • 2,592
  • 12
  • 30
  • 40
majidarif
  • 18,694
  • 16
  • 88
  • 133
1

Here is in Java one, someone may need it.

  1. First, you can list all labels like in example below. For more information check here
    public void listLabels(final Gmail service, final String userId) throws IOException {
            ListLabelsResponse response = service.users().labels().list(userId).execute();
            List<Label> labels = response.getLabels();
            for (Label label : labels) {
              System.out.println("Label: " + label.toPrettyString());
            }
          }
  1. Modify the required labels for each message is associated with it, like so: More information about it goes here
    public void markAsRead(final Gmail service, final String userId, final String messageId) throws IOException {
            ModifyMessageRequest mods =
                    new ModifyMessageRequest()
                    .setAddLabelIds(Collections.singletonList("INBOX"))
                    .setRemoveLabelIds(Collections.singletonList("UNREAD"));
            Message message = null;
        
            if(Objects.nonNull(messageId)) {
              message = service.users().messages().modify(userId, messageId, mods).execute();
              System.out.println("Message id marked as read: " + message.getId());
            }
          }
kohane15
  • 809
  • 12
  • 16
0

Example in iOS Swift:

class func markAsReadMessage(messageId: String) {
    let appd = UIApplication.sharedApplication().delegate as! AppDelegate
    println("marking mail as read \(messageId)")
    let query = GTLQueryGmail.queryForUsersMessagesModify()
    query.identifier = messageId
    query.removeLabelIds = ["UNREAD"]
    appd.service.executeQuery(query, completionHandler: { (ticket, response, error) -> Void in
        println("ticket \(ticket)")
        println("response \(response)")
        println("error \(error)")
    })
}
kohane15
  • 809
  • 12
  • 16
jose920405
  • 7,982
  • 6
  • 45
  • 71
0

There are a two steps to achieve this. I use the Gmail Client Library, available here, specifically from the examples folder get_token.php and user-gmail.php: PHP Gmail Client Library

I also used the function for modification, available here: Gmail API Modify Message Page

First you must specify that you wish to have Modify rights. In the examples, they only show you the read-only scope, but you can add other scopes in the array.

$client->addScope(implode(' ', array(Google_Service_Gmail::GMAIL_READONLY, Google_Service_Gmail::GMAIL_MODIFY)));

I wanted to keep the same labels, and mark the message as read. So for a single message:

$arrLabels = $single_message->labelIds;
foreach($arrLabels as $label_index=>$label) {
    if ($label=="UNREAD") {
        unset($arrLabels[$label_index]);
    }
}

Now you can send the modification request, and the message will be removed from the UNREAD list on your Gmail account.

modifyMessage($service, "me", $mlist->id, $arrLabels, array("UNREAD"));

where "me" is the user_id.

kohane15
  • 809
  • 12
  • 16
Nicolas Giszpenc
  • 677
  • 6
  • 11