Skip to content

Instantly share code, notes, and snippets.

@mping
Forked from bartojs/build.boot
Created May 27, 2017 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mping/c5b702751dc9bb510be0ceec68352221 to your computer and use it in GitHub Desktop.
Save mping/c5b702751dc9bb510be0ceec68352221 to your computer and use it in GitHub Desktop.
gmail rest api java/clojure example with oauth2 and labels
;; 1) first goto https://console.developers.google.com/start/api?id=gmail
;; -- to turn on gmail api for your account
;; 2) then create a oauth consent with app name
;; 3) then add oauth clientid and download to ./clientsecret.json
;; 4) boot run
;; -- when running first time a browser will open to accept authorizaton
(set-env! :dependencies '[[com.google.apis/google-api-services-gmail "v1-rev34-1.21.0"]
[com.google.api-client/google-api-client "1.20.0"]
[com.google.oauth-client/google-oauth-client-jetty "1.20.0"]])
(require '[clojure.java.io :as io])
(import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp
com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver
com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow$Builder
com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets
com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
com.google.api.client.http.HttpTransport
com.google.api.client.json.jackson2.JacksonFactory
com.google.api.client.util.store.FileDataStoreFactory
com.google.api.services.gmail.GmailScopes
com.google.api.services.gmail.Gmail$Builder)
(def transport (GoogleNetHttpTransport/newTrustedTransport))
(def jackson (JacksonFactory/getDefaultInstance))
(defn auth []
(println "auth")
(let [datastore (FileDataStoreFactory. (io/file "."))
secrets (GoogleClientSecrets/load jackson (io/reader "clientsecret.json"))
scopes [GmailScopes/GMAIL_LABELS]
flow (.. (GoogleAuthorizationCodeFlow$Builder. transport jackson secrets scopes) (setDataStoreFactory datastore) (setAccessType "offline") (build))]
(.authorize (AuthorizationCodeInstalledApp. flow (LocalServerReceiver.)) "user")))
(defn gmail [cred]
(println "gmail")
(.. (Gmail$Builder. transport jackson cred) (setApplicationName "Test Gmail") (build)))
(deftask run []
(println "run")
(let [g (gmail (auth))]
(doseq [l (.. g (users) (labels) (list "me") (execute) (getLabels))]
(println (.getName l)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment