stuncloud
2/1/2016 - 5:01 AM

gmail受信サンプル

gmail受信サンプル

call Module_Gmail.uws

Gmail.Print()

id = getid(GET_LOGPRINT_WIN)
while status(id, ST_VISIBLE)
    sleep(0.1)
wend
module Gmail
    // クライアントIDとシークレットはGoogle APIs Consoleで発行してください
    dim CLIENT_ID     = "xxxxxxxxxxxx.apps.googleusercontent.com"
    dim CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxx"
    dim ACCESS_TOKEN
    dim REFRESH_TOKEN
    dim AUTHORIZATION_CODE

    procedure Gmail
        ACCESS_TOKEN  = readini("token", "ACCESS_TOKEN")
        REFRESH_TOKEN = readini("token", "REFRESH_TOKEN")
    fend

    procedure Print(index = 0, charset = "utf-8")
        // charset で指定するのは HKEY_CLASSES_ROOT\MIME\Database\Charset のサブキー群の名前
        if length(ACCESS_TOKEN) then
            list = GetList()
            if list = EMPTY then
                if RefreshAccessToken() then
                    msgbox("アクセストークンを再取得しました<#CR>再実行してください")
                else
                    msgbox("アクセストークンの再取得に失敗しました")
                endif
            endif
            getoleitem(list.messages)
            id = ALL_OLE_ITEM[index].id
            mail = GetMail(id)
            // for header in getoleitem(mail.payload.headers)
            //     print header.name
            //     print header.value
            //     print
            // next
            try
                if mail.payload.body.size then
                    print Base64ToString(mail.payload.body.data, charset)
                else
                    for part in getoleitem(mail.payload.parts)
                        print Base64ToString(part.body.data, charset)
                    next
                endif
            except
                print TRY_ERRLINE
                print TRY_ERRMSG
            endtry
            
        else
            if msgbox("アクセストークンを取得します") = BTN_CANCEL then exit
            GetAuthCode()
            if length(AUTHORIZATION_CODE) then
                if GetAccessToken() then
                    msgbox("アクセストークンを取得しました<#CR>再実行するとメールを取得できます")
                else
                    msgbox("アクセストークンの取得に失敗しました")
                endif
            endif
        endif
    fend
    
    procedure GetAuthCode()
        shell = createoleobj("Shell.Application")
        shell.ShellExecute("https://accounts.google.com/o/oauth2/auth?client_id=" + CLIENT_ID + "&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/gmail.readonly&response_type=code&approval_prompt=force&access_type=offline")

        code = input("ブラウザに表示されたコードをコピーしてください")
        if length(code) then
            AUTHORIZATION_CODE = code
        endif
    fend
    
    function GetAccessToken()
        hashtbl data

        data["client_id"]     = "client_id=" + CLIENT_ID
        data["client_secret"] = "client_secret=" + CLIENT_SECRET
        data["redirect_uri"]  = "redirect_uri=urn:ietf:wg:oauth:2.0:oob"
        data["grant_type"]    = "grant_type=authorization_code"
        data["scope"]         = "scope=https://www.googleapis.com/auth/gmail.readonly"
        data["code"]          = "code=" + AUTHORIZATION_CODE

        result = FALSE
        json = GetToken(join(data, "&"))
        if json <> empty then
            with json
                ACCESS_TOKEN  = .access_token
                REFRESH_TOKEN = .refresh_token
                writeini("token", "ACCESS_TOKEN", ACCESS_TOKEN)
                writeini("token", "REFRESH_TOKEN", REFRESH_TOKEN)
            endwith
            result = TRUE
        endif
    fend

    function RefreshAccessToken()
        hashtbl data

        data["client_id"]     = "client_id=" + CLIENT_ID
        data["client_secret"] = "client_secret=" + CLIENT_SECRET
        data["grant_type"]    = "grant_type=refresh_token"
        data["refresh_token"] = "refresh_token=" + REFRESH_TOKEN

        result = FALSE
        json = GetToken(join(data, "&"))
        if json <> empty then
            with json
                ACCESS_TOKEN  = .access_token
                writeini("token", "ACCESS_TOKEN", ACCESS_TOKEN)
            endwith
            result = TRUE
        endif
    fend
    
    function GetToken(data)
        with createoleobj("Msxml2.XMLHTTP")
            .open("POST", "https://accounts.google.com/o/oauth2/token", FALSE)
            .setRequestHeader("content-type", "application/x-www-form-urlencoded")
            .send(data)
            result = EMPTY
            if .status = 200 then
                result = ParseJson(.responseText)
            endif
        endwith
    fend
    
    function GetList()
        with createoleobj("Msxml2.XMLHTTP")
            .open("GET", "https://www.googleapis.com/gmail/v1/users/me/messages/", FALSE)
            .setRequestHeader("Authorization", "Bearer " + ACCESS_TOKEN)
            .send()
            result = EMPTY
            if .status = 200 then
                result = ParseJson(.responseText)
            else
                msgbox(.statusText)
            endif
        endwith
    fend
    
    function GetMail(id)
        with createoleobj("Msxml2.XMLHTTP")
            .open("GET", "https://www.googleapis.com/gmail/v1/users/me/messages/" + id, FALSE)
            .setRequestHeader("Authorization", "Bearer " + ACCESS_TOKEN)
            .send()
            result = EMPTY
            if .status = 200 then
                result = ParseJson(.responseText)
            else
                msgbox(.statusText)
            endif
        endwith
    fend
    

    function ParseJson(json)
        with createoleobj("ScriptControl")
            .Language = "JScript"
            result = .Eval("(" + json + ");")
        endwith
    fend
    
    function Base64ToString(b64, charset)
        try
            with createoleobj("Microsoft.XMLDOM")
                with .createElement("tmp")
                    .dataType = "bin.base64"
                    .text = replace(replace(b64, "_", "/"), "-", "+")
                    bin = .nodeTypedValue
                endwith
            endwith

            with createoleobj("ADODB.Stream")
                .Open()
                .Type = 1
                .Write(bin)
                .Position = 0
                .Type = 2
                .Charset = charset
                result = .ReadText()
                .Close()
            endwith
        except
            print TRY_ERRLINE
            print TRY_ERRMSG
            result = NULL
        endtry
    fend

endmodule