How to Retrieve Replied Emails for Gmail

Gists

Description :

This sample script is for retrieving emails which replied for received mails. Because there are no samples which confirm whether the owner (me) replied to the received mails, I created this. The point is as follows.

  • When there are more than 2 messages in a thread, there might be a possibility to have replied.
  • For more than 2 messages in a thread
    • The email address of “from” for the 1st message is the sender’s address.
    • When the email address of “to” of after 2nd messages is the same to that of “from” of 1st one, it is indicates that the thread was replied by owner.

This sample script is made of Google Apps Script (GAS). But also this can be applied to other languages.

GAS Library - ProjectApp2

Overview

This is a GAS project library for Google Apps Script (GAS). This library can be used for the projects of both standalone script type and container-bound script type.

Description

There are Class SpreadsheetApp and Class DocumentApp for operating spreadsheet and document, respectively. But there is no Class for operating GAS project. If there is such Class ProjectApp, GAS project can be directly operated by GAS script. I thought that this will lead to new applications, and created ProjectApp. On the other hand, as a CLI tool for operating GAS project, there has already been ggsrun.

google.script.run and jQuery.Deferred

google.script.run doesn’t return values. So I tried this using jQuery.Deferred.

GAS : Code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function getValues(e) {
  return e + "hoge";
}

HTML : index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
<body>
  <input type="button" id="button" value="ok">
  <div id="result"></div>

  <script>
    $(() => {
      $("#button").click(() => {
        var str = "fuga";
        googleScriptRun(str).then((res) => {
          $('#result').text(res);
        });
      });
    });

    function googleScriptRun(str) {
      var d = new $.Deferred();
      google.script.run.withSuccessHandler((res) => {d.resolve(res)}).getValues(str);
      return d.promise();
    }
  </script>
</body>

Result :

fugahoge

Above sample can be also written as follows.

Updated ggsrun to v140

ggsrun was updated to v.1.4.0

You can read “How to install” at here.

Copying and Overwriting GAS Project

Gists

Pattern 1

This is a sample script for copying GAS project to a container-bound script of Google Docs (Spreadsheet, Document and Form (and Slides)). The project is created as a new project.

In order to use this sample, please do the following installation flow.

If you use this sample script, at first, please test using a new project and new Google Docs. By this, please understand the work of this script.

Batching Requests for Google Apps Script

Gists

There is the bathing requests in the Google APIs. The bathing requests can use the several API calls as a single HTTP request. By using this, for example, users can modify filenames of a lot of files on Google Drive. But there are limitations for the number of API calls which can process in one batch request. For example, Drive API can be used the maximum of 100 calls in one batch request.

Zaif API for Google Apps Script

Gists

This sample script is for using Zaif API by Google Apps Script.

The following go script is a sample at Zaif API.

package main

import (
    "fmt"
    "time"
    "strconv"
    "crypto/hmac"
    "crypto/sha512"
    "io/ioutil"
    "net/http"
    "encoding/hex"
    "net/url"
    "strings"
)

var key = "<your_key>"
var secret = "<your_secret>"

func main() {

    uri := "https://api.zaif.jp/tapi"
    values := url.Values{}
    values.Add("method", "get_info")
    values.Add("nonce", strconv.FormatInt(time.Now().Unix(), 10))

    encodedParams := values.Encode()
    req, _ := http.NewRequest("POST", uri, strings.NewReader(encodedParams))

    hash := hmac.New(sha512.New, []byte(secret))
    hash.Write([]byte(encodedParams))
    signature := hex.EncodeToString(hash.Sum(nil))

    req.Header.Add("Key", key)
    req.Header.Add("Sign", signature)
    client := new(http.Client)
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    byteArray, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(byteArray))
}

When this is converted to GAS, the script is as follows.

Bittrex API for Google Apps Script

Gists

This sample script is for using Bittrex API by Google Apps Script.

The following PHP script is a sample at bittrex.com.

$apikey='xxx';
$apisecret='xxx';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/market/getopenorders?apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);

When this is converted to GAS, the script is as follows.

function main() {
  var apikey = '#####'; // Please input your key.
  var apisecret = '#####'; // Please input your secret.

  var nonce = Number(new Date().getTime() / 1000).toFixed(0);
  var uri = 'https://bittrex.com/api/v1.1/market/getopenorders?apikey=' + apikey + '&nonce=' + nonce;
  var sign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, uri, apisecret);
  sign = sign.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2);}).join("");
  var params = {
    method: "get",
    headers: {Apisign: sign}
  }
  var res = UrlFetchApp.fetch(uri, params);
  Logger.log(res.getContentText())
}

Binance API for Google Apps Script

Gists

This sample script is for using Binance API by Google Apps Script. This script encryptes “signature” like samples. In this script, “Example 1: As a query string” is used, and it retrieves “All orders (SIGNED)” by “GET”.

function main() {
    var key = '#####'; // Please input your key.
    var secret = '#####'; // Please input your secret.
    var api = "/api/v3/allOrders"; // Please input API Endpoint you want.
    var timestamp = Number(new Date().getTime()).toFixed(0);
    var string = "symbol=LTCBTC&timestamp=" + timestamp; // Please input query parameters for the inputterd API.

    var baseUrl = "https://api.binance.com";
    var signature = Utilities.computeHmacSha256Signature(string, secret);
    signature = signature.map(function(e) {
        var v = (e < 0 ? e + 256 : e).toString(16);
        return v.length == 1 ? "0" + v : v;
    }).join("");
    var query = "?" + string + "&signature=" + signature;
    var params = {
        'method': 'get',
        'headers': {'X-MBX-APIKEY': key},
        'muteHttpExceptions': true
    };
    var data = UrlFetchApp.fetch(baseUrl + api + query, params);
    Logger.log(data.getContentText())
}