Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Golang Gmail Api #37

Open
reddragon09 opened this issue Oct 9, 2019 · 4 comments
Open

Golang Gmail Api #37

reddragon09 opened this issue Oct 9, 2019 · 4 comments

Comments

@reddragon09
Copy link
Author

reddragon09 commented Oct 9, 2019

My code

package mail_process

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"golang.org/x/net/context"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/gmail/v1"
)

// MailsController operations for Mails
type CloneMailsController struct {
	beego.Controller
	//libs.Middleware
}

// URLMapping ...
func (c *CloneMailsController) URLMapping() {
	c.Mapping("Post", c.Post)
}

// CloneMail
// @Title CloneMail
// @Description CloneMail
// @Param	Authorization	header	string	false	"token"
// @Success 201 {int}
// @Failure 403 body is empty <br> 211 Variable is not json type <br> 217 Variable required <br> 303 Save data failures
//
// @router / [post]
func (c *CloneMailsController) CloneMail() {
	GetMail()
	c.Data["json"] = ""
	c.ServeJSON()
}

//Get mail from mail server
func GetMail() {
	b, err := ioutil.ReadFile("./storage/mail_process/credentials.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}

	// If modifying these scopes, delete your previously saved token.json.
	config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(config)
	fmt.Println("---------------------------------------------------------------")
	fmt.Println(config)
	fmt.Println(client)
	srv, err := gmail.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve Gmail client: %v", err)
	}
	fmt.Println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
	fmt.Println(srv)
	user := "me"
	r, err := srv.Users.Labels.List(user).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)
	}
}

// Retrieve a token, saves the token, then returns the generated client.
func getClient(config *oauth2.Config) *http.Client {
	// The file token.json stores the user's access and refresh tokens, and is
	// created automatically when the authorization flow completes for the first
	// time.
	tokFile := "./storage/mail_process/token.json"
	tok, err := tokenFromFile(tokFile)
	if err != nil {
		tok = getTokenFromWeb(config)
		saveToken(tokFile, tok)
	}
	return config.Client(context.Background(), tok)
}

// Request a token from the web, then returns the retrieved token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
	authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
	fmt.Printf("Go to the following link in your browser then type the "+
		"authorization code: \n%v\n", authURL)

	var authCode string = "4/rwFbig35HHvO6fps4tsup3wNP1ZW8onrmHxa1_kEq5BpYst0udZ8bkw"
	if _, err := fmt.Scan(&authCode); err != nil {
		log.Fatalf("Unable to read authorization code: %v", err)
	}

	tok, err := config.Exchange(context.TODO(), authCode)
	if err != nil {
		log.Fatalf("Unable to retrieve token from web: %v", err)
	}
	return tok
}

// Retrieves a token from a local file.
func tokenFromFile(file string) (*oauth2.Token, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	tok := &oauth2.Token{}
	err = json.NewDecoder(f).Decode(tok)
	fmt.Println(f)
	fmt.Println(tok)
	return tok, err
}

// Saves a token to a file path.
func saveToken(path string, token *oauth2.Token) {
	fmt.Printf("Saving credential file to: %s\n", path)
	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		log.Fatalf("Unable to cache oauth token: %v", err)
	}
	defer f.Close()
	json.NewEncoder(f).Encode(token)
}
```
`

@hi-Ernest
Copy link

hi-Ernest commented Jul 24, 2022

you need add your account as test user of OAuth consent screen

@etiennepericat
Copy link

exact same problem here, even with test account properly saved, do you have any fix ?

@porridge
Copy link

From your source:

	var authCode string = "4/rwFbig35HHvO6fps4tsup3wNP1ZW8onrmHxa1_kEq5BpYst0udZ8bkw"

This variable must be empty for fmt.Scan to work as intended. But in the 2023 era even if you fix that, you'll hit another problem as described in #76 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants