Last active
March 23, 2023 11:29
-
-
Save bartojs/d8a65f89e82074a46b8e to your computer and use it in GitHub Desktop.
gmail rest api java/clojure example with oauth2 and labels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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