Skip to content

Instantly share code, notes, and snippets.

@silverark
Created October 2, 2019 21:56
Show Gist options
  • Save silverark/7ffd4505076c991596165596b95474f3 to your computer and use it in GitHub Desktop.
Save silverark/7ffd4505076c991596165596b95474f3 to your computer and use it in GitHub Desktop.
Access Gmail account with a service Account in Go (Golang)
package main
import (
"fmt"
"google.golang.org/api/gmail/v1"
"io/ioutil"
"log"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/option"
)
// Path to the Service Account's Private Key file
var ServiceAccountFilePath = "your-private-key-for-service-account.json"
// Build and returns a Gmail service object authorized with Service Account
func CreateGmailService(userEmail string) (*gmail.Service, error) {
ctx := context.Background()
jsonCredentials, err := ioutil.ReadFile(ServiceAccountFilePath)
if err != nil {
return nil, err
}
config, err := google.JWTConfigFromJSON(jsonCredentials, gmail.MailGoogleComScope)
if err != nil {
return nil, fmt.Errorf("JWTConfigFromJSON: %v", err)
}
config.Subject = userEmail
ts := config.TokenSource(ctx)
srv, err := gmail.NewService(ctx, option.WithTokenSource(ts))
if err != nil {
return nil, fmt.Errorf("NewService: %v", err)
}
return srv, nil
}
func main() {
emailId := "your.email@yourdomain.com"
service, err := CreateGmailService(emailId)
if err != nil {
log.Fatalf("Unable to retrieve labels: %v", err)
}
r, err := service.Users.Labels.List(emailId).Do()
if err != nil {
log.Fatalf("Unable to retrieve labels: %v", err)
}
if len(r.Labels) == 0 {
fmt.Println("No labels found.")
return
}
fmt.Println("Labels:")
for _, l := range r.Labels {
fmt.Printf("- %s\n", l.Name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment