title: search messages with Gmail API in Google Apps Script
body: <p>i've searched through StackOverflow with (small) success, so I ask help to a more expert coder than me.</p>
  
  <p>I've read this topic on SO <a href="https://stackoverflow.com/questions/30798530/gmailapp-add-label-to-specific-message-not-the-thread">gmailapp-add-label-to-specific-message-not-the-thread</a> which leads me to this <a href="https://gist.github.com/mogsdad/6515581#label-a-message" rel="nofollow noreferrer">GIST</a>, where I've taken the code for labelling a single message (and not the entire thread).</p>
  
  <p>Now i need to use the search functions of the Gmail API in Google Apps Script; I've found a Javascript snippet on Google Developer's Site <a href="https://developers.google.com/gmail/api/v1/reference/users/messages/list#http-request" rel="nofollow noreferrer">here</a>. I'm trying to adapt this code using the code found in GIST as example, but without success.</p>
  
  <p>I need the search function to get an array of message ID's to pass to another function (that works, for now ;) ).</p>
  
  <p>Here's the code I've wrote:</p>
  
  <pre><code>/**
   * Retrieve Messages in user's mailbox matching query.
   *
   * @param  {String} userId User's email address. The special value 'me'
   * can be used to indicate the authenticated user.
   * @param  {String} query String used to filter the Messages listed.
   * @param  {Function} callback Function to call when the request is complete.
   */
  function GAPIlistMessages(userId, query) { //callback option removed from original code
  
   // GET https://www.googleapis.com/gmail/v1/users/userId/messages
    var url = 'https://www.googleapis.com/gmail/v1/users/${userId}/messages'
    .replace("${userId}","me")
              var headers = {
      Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
    };
  
      var request = {
        'userId': userId,
        'q': query
    };
  
    var params = {
      method: "GET",
      contentType: "application/json",
      headers: headers,
      muteHttpExceptions: true, // for debugging
      payload: JSON.stringify(request)
      };
  
    var check = UrlFetchApp.getRequest(url, params); // for debugging
    var response = UrlFetchApp.fetch(url, params);
  
    var result = response.getResponseCode();
    if (result == '200') {  // OK
      var msgIds = JSON.parse(response.getContentText()).msgIds;
    Logger.log(msgIds)
    }
    else {
      // This is only needed when muteHttpExceptions == true
      var err = JSON.parse(response.getContentText());
      throw new Error( 'Error (' + result + ") " + err.error.message );
    } 
  }
  </code></pre>
  
  <p>When i launch the function, passing this parameters:
  userId = 'me'
  query = 'deliveredto:myemail+test@mydomain.com'</p>
  
  <p>I receive this error</p>
  
  <pre><code>[16-02-24 06:37:29:218 PST] Avvio dell'esecuzione
  [16-02-24 06:37:29:236 PST] ScriptApp.getOAuthToken() [0 secondi]
  [16-02-24 06:37:29:237 PST] UrlFetchApp.getRequest([https://www.googleapis.com/gmail/v1/users/me/messages, {headers={Authorization=Bearer &lt;&lt;&lt;token removed&gt;&gt;&gt;}, method=GET, payload={"userId":"me",...) [0 secondi]
  [16-02-24 06:37:29:308 PST] UrlFetchApp.fetch([https://www.googleapis.com/gmail/v1/users/me/messages, {headers={Authorization=Bearer &lt;&lt;&lt;token removed&gt;&gt;&gt;}, method=GET, payload={"userId":"me",...) [0,07 secondi]
  [16-02-24 06:37:29:308 PST] HTTPResponse.getResponseCode() [0 secondi]
  [16-02-24 06:37:29:308 PST] HTTPResponse.getContentText() [0 secondi]
  [16-02-24 06:37:29:311 PST] Esecuzione non riuscita: Error: Error (400) 'raw' RFC822 payload message string or uploading message via /upload/* URL required (riga 212, file "Test Tools") [0,075 secondi di esecuzione totale]
  </code></pre>
  
  <p>I feel that I'm close to the solution, but I can't figure out where is the problem. 
  Any help would be <strong>VERY</strong> appreciated</p>
  
  <p><em>Manuel</em></p>