Users.messages: modify

Requires authorization

Modifies the labels on the specified message. Try it now or see an example.

Request

HTTP request

POST https://www.googleapis.com/gmail/v1/users/userId/messages/id/modify

Parameters

Parameter name Value Description
Path parameters
id string The ID of the message to modify.
userId string The user's email address. The special value me can be used to indicate the authenticated user.

Authorization

This request requires authorization with at least one of the following scopes (read more about authentication and authorization).

Scope
https://mail.google.com/
https://www.googleapis.com/auth/gmail.modify

Request body

In the request body, supply data with the following structure:

{
  "addLabelIds": [
    string
  ],
  "removeLabelIds": [
    string
  ]
}
Property name Value Description Notes
addLabelIds[] list A list of IDs of labels to add to this message.
removeLabelIds[] list A list IDs of labels to remove from this message.

Response

If successful, this method returns a Users.messages resource in the response body.

Examples

Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).

Java

Uses the Java client library.

import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import com.google.api.services.gmail.model.ModifyMessageRequest;

import java.io.IOException;
import java.util.List;

// ...

public class MyClass {

  // ...


  /**
   * Modify the labels a message is associated with.
   *
   * @param service Authorized Gmail API instance.
   * @param userId User's email address. The special value "me"
   * can be used to indicate the authenticated user.
   * @param messageId ID of Message to Modify.
   * @param labelsToAdd List of label ids to add.
   * @param labelsToRemove List of label ids to remove.
   * @throws IOException
   */
  public static void modifyMessage(Gmail service, String userId, String messageId,
      List<String> labelsToAdd, List<String> labelsToRemove) throws IOException {
    ModifyMessageRequest mods = new ModifyMessageRequest().setAddLabelIds(labelsToAdd)
        .setRemoveLabelIds(labelsToRemove);
    Message message = service.users().messages().modify(userId, messageId, mods).execute();

    System.out.println("Message id: " + message.getId());
    System.out.println(message.toPrettyString());
  }

  // ...

}

.NET

Uses the .NET client library.

using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;

using System.Collections.Generic;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Modify the Labels a Message is associated with.
  /// </summary>
  /// <param name="service">Gmail API service instance.</param>
  /// <param name="userId">User's email address. The special value "me"
  /// can be used to indicate the authenticated user.</param>
  /// <param name="messageId">ID of Message to modify.</param>
  /// <param name="labelsToAdd">List of label ids to add.</param>
  /// <param name="labelsToRemove">List of label ids to remove.</param>
  public static Message ModifyMessage(GmailService service, String userId,
      String messageId, List<String> labelsToAdd, List<String> labelsToRemove)
  {
      ModifyMessageRequest mods = new ModifyMessageRequest();
      mods.AddLabelIds = labelsToAdd;
      mods.RemoveLabelIds = labelsToRemove;

      try
      {
          return service.Users.Messages.Modify(mods, userId, messageId).Execute();
      }
      catch (Exception e)
      {
          Console.WriteLine("An error occurred: " + e.Message);
      }

      return null;
  }

  // ...

}

PHP

Does not use a client library.

/**
 * Modify the Labels a Message is associated with.
 *
 * @param  Google_Service_Gmail $service Authorized Gmail API instance.
 * @param  string $userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  string $messageId ID of Message to modify.
 * @param  array $labelsToAdd Array of Labels to add.
 * @param  array $labelsToRemove Array of Labels to remove.
 * @return Google_Service_Gmail_Message Modified Message.
 */
function modifyMessage($service, $userId, $messageId, $labelsToAdd, $labelsToRemove) {
  $mods = new Google_Service_Gmail_ModifyMessageRequest();
  $mods->setAddLabelIds($labelsToAdd);
  $mods->setRemoveLabelIds($labelsToRemove);
  try {
    $message = $service->users_messages->modify($userId, $messageId, $mods);
    print 'Message with ID: ' . $messageId . ' successfully modified.';
    return $message;
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
  }
}

Python

Uses the Python client library.

"""Modify an existing Message's Labels.
"""

from apiclient import errors


def ModifyMessage(service, user_id, msg_id, msg_labels):
  """Modify the Labels on the given Message.

  Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    msg_id: The id of the message required.
    msg_labels: The change in labels.

  Returns:
    Modified message, containing updated labelIds, id and threadId.
  """
  try:
    message = service.users().messages().modify(userId=user_id, id=msg_id,
                                                body=msg_labels).execute()

    label_ids = message['labelIds']

    print 'Message ID: %s - With Label IDs %s' % (msg_id, label_ids)
    return message
  except errors.HttpError, error:
    print 'An error occurred: %s' % error


def CreateMsgLabels():
  """Create object to update labels.

  Returns:
    A label update object.
  """
  return {'removeLabelIds': [], 'addLabelIds': ['UNREAD', 'INBOX', 'Label_2']}

JavaScript

Does not use a client library.

/**
 * Modify the Labels a Message is associated with.
 *
 * @param  {String} userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  {String} messageId ID of Message to modify.
 * @param  {Array} labelsToAdd Array of Labels to add.
 * @param  {Array} labelsToRemove Array of Labels to remove.
 * @param  {Function} callback Function to call when the request is complete.
 */
function modifyMessage(userId, messageId, labelsToAdd, labelsToRemove, callback) {
  var request = gapi.client.gmail.users.messages.modify({
    'userId': userId,
    'id': messageId,
    'addLabelIds': labelsToAdd,
    'removeLabelIds': labelsToRemove
  });
  request.execute(callback);
}

Try it!

Use the APIs Explorer below to call this method on live data and see the response.

Send feedback about...

Need help? Visit our support page.