Mark as read mail method

How do I mark mail as read using the Gmail API?

I have a stream of emails

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

      

but it doesn't have a markRead method like the Gmail API site, it has to do that.

+5


source to share


7 replies


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



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

+9


source


Since I came here looking for this C # answer, 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();

      



Works with pleasure.

+4


source


In the 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);
    });

      

+4


source


Ios swift example

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)")
        })
    }

      

0


source


There are two steps to this. I am using the Gmail client library available here, specifically from the get_token.php and user-gmail.php examples folder: PHP Gmail Client Library

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

First, you must indicate that you want to have edit rights. In the examples, they only display a read-only area, but you can add other areas to the array.

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

      

I wanted to keep the same tags and mark the message as read. So, for one post:

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

      

You can now submit a change request and the message will be removed from the UNREAD list in your Gmail account.

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

      

where "me" is user_id.

0


source


Here's one in Java, someone might need it.

  1. First, you can list all the labels as in the 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. Change the required labels for each post associated with it, like this: More on this 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());
        }
      }

      

0


source


In case anyone else stumbles upon this using the Golang API. Here's how you can do it:

msg, err := gmail.Users.Messages.Modify("me", msg.Id, &gmail.ModifyMessageRequest{
   RemoveLabelIds: []string{"UNREAD"},
}).Do()

      

Hope this helps!

0


source







All Articles