JWT token expired when Go app is installed - go

I am working on a SAAS based product. I am using JWT method to authenticate the logged in users in the system. The product is developed on Go on the backend with gin framework for routing.
Problem
When a user log in then its JWT token is generated and works well. Now the user did not logged out but closed the browser tab or window. Before he is back, the go app is re-installed with install command. Now the user come back and access his account, the token is expired and he could not see any of his details.
Following is the code to generate token while login:
func CreateToken(user models.User, c *gin.Context) (string, error){
var ip, userAgent string
keyError := InitKeys()
if keyError != nil{
return "", keyError
}
if values, _ := c.Request.Header["Ip"]; len(values) > 0 {
ip = values[0]
}
if values, _ := c.Request.Header["User-Agent"]; len(values) > 0{
userAgent = values[0]
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.MapClaims{
"email": user.EmailId,
"exp": time.Now().Add(time.Hour * 8760).Unix(),
"role": user.Role,
"name": user.FirstName+" "+user.LastName,
"ip": ip,
"user_agent": userAgent,
"id": user.Id,
})
config.CurrentUserId = user.Id
models.CurrentUser = user
/* Sign and get the complete encoded token as a string */
tokenString, err := token.SignedString([]byte(config.SignKey))
return tokenString, err
}
func InitKeys()(err error){
SignKey, err = ioutil.ReadFile(GetBasePath()+PrivateKeyPath)
if err != nil {
return err
}
VerifyKey, err = ioutil.ReadFile(GetBasePath()+PublicKeyPath)
if err != nil {
return err
}
return nil
}
Now to decode and match the token following function is used:
func ParseJWTToken(c *gin.Context){
merchantDb := models.MerchantDatabase{ c.Keys["merchant_db"].(string) }
merchantDatabase := make(map[string]interface{})
if values, _ := c.Request.Header["Authorization"]; len(values) > 0 {
bearer := strings.Split(c.Request.Header["Authorization"][0], "Bearer")
bearerToken := strings.TrimSpace(bearer[1])
_, err := merchantDb.GetSession(bson.M{"token": bearerToken})
if err != nil{
errMsg := "Failed: Unauthorized Access."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
err,
}
controllers.GetResponse(c, response)
c.Abort()
}else{
var userAgent string
var userAgentCheck bool
if values, _ := c.Request.Header["User-Agent"]; len(values) > 0 {
userAgent = values[0]
}
_ = config.InitKeys()
token, err := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {
return config.SignKey, nil
})
if len (token.Claims.(jwt.MapClaims)) > 0{
for key, claim := range token.Claims.(jwt.MapClaims) {
if key == "user_agent"{
if claim == userAgent{
userAgentCheck = true
}
}
if key == "role"{
role = claim.(string)
}
if key == "id"{
userId = claim.(float64)
}
if key == "name"{
userName = claim.(string)
}
}
}
merchantDatabase["userid"] = userId
merchantDatabase["role"] = role
merchantDatabase["username"] = userName
c.Keys = merchantDatabase
if err == nil && token.Valid && userAgentCheck == true {
c.Next()
} else {
errMsg := "Failed: Invalid Token."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
nil,
}
controllers.GetResponse(c, response)
c.Abort()
}
}
}else{
errMsg := "Failed: Unauthorized Access."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
"Missing Authorization Header",
}
controllers.GetResponse(c, response)
c.Abort()
}
}
I am not able to detect what I am missing. Please look into the code and guide me what should I do in this case.

Related

golang Fiber no getting user register ID

I am learning fiber framework and JWT Auth. The register Func and Login Func correctly saves the user Id in the database. The cookie and JWT are are retrieved correctly and displayed the cookie and persisted on the front end. When I attempt to get the login UserId in the Controller I'm not expecting them to be 0.
I leave the code hopping have some orientation.
// Midleware:
const SecretKey = "secret"
func IsAuthenticated(c *fiber.Ctx) error {
cookie := c.Cookies("jwt")
token, err := jwt.ParseWithClaims(cookie, &jwt.RegisteredClaims{}, func(token *jwt.Token)
(interface{}, error) {
return []byte(SecretKey), nil
})
if err != nil || !token.Valid {
c.Status(fiber.StatusUnauthorized)
return c.JSON(fiber.Map{
"message": "unauthenticated",
})
}
return c.Next()
}
func GetUserId(c *fiber.Ctx) (uint, error) {
cookie := c.Cookies("jwt")
log.Println("Cookie .........: ", cookie)
token, err := jwt.ParseWithClaims(cookie, &jwt.RegisteredClaims{}, func(token *jwt.Token)
(interface{}, error) {
return []byte(SecretKey), nil
})
log.Println("Token .........: ", token)
log.Println("Error .........: ", err)
if err != nil {
return 0, err
}
// var user dto.User
// expireTime := time.Now().Add(24 * time.Hour)
// payloads := jwt.RegisteredClaims{
// Subject: strconv.Itoa(int(user.Id)),
// ExpiresAt: &jwt.NumericDate{Time: expireTime},
// }
payload := token.Claims.(*jwt.RegisteredClaims)
id, _ := strconv.Atoi(payload.Subject)
return uint(id), nil
}
func GenerateJWT(id uint) (string, error) {
expireTime := time.Now().Add(24 * time.Hour)
var user dto.User
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256,
jwt.RegisteredClaims{
Subject: strconv.Itoa(int(user.Id)),
ExpiresAt: &jwt.NumericDate{Time: expireTime},
}).SignedString([]byte(SecretKey))
if err != nil {
log.Println(err)
}
return token, err
}
//Controller:
func User(c *fiber.Ctx) error {
var user dto.User
id, err := middlewares.GetUserId(c)
log.Println(id)
if err != nil {
return err
}
confmysql.DB.Where("id = ?", id).First(&user)
return c.JSON(user)
}
i answered this question before
u can access that answer here
if u have question comment here for me

Variable (token) holding parsed token is returning nil

My VerifyToken is returning nil and, despite many attempts, I have been unable to discover why.
Also in each function(ExtractToken(),VerifyToken()) I tried to print out the token to confirm if the token exists. The parsed token from the VerifyToken func is nil and I had tried ways to make it work but it still returning nil.
My .env file contains:
ACCESS_SECRET = "jdnfksdmfksd"
REFRESH_SECRET = "mcmvmkmsdnfsdmfdsjf"
And my application code follows:
//types.TokenDetails
type TokenDetails struct {
AccessToken string
AccessUuid string
UserId uint64
AtExp int64
RefreshToken string
RefreshUuid string
RtExp int64
}
func CreateToken(userId uint64, r *http.Request) (*types.TokenDetails, error) {
var err error
td := &types.TokenDetails{}
td.AccessUuid = uuid.NewV4().String()
//td.UserId = userId
td.AtExp = time.Now().Add(time.Minute * 15).Unix()
atClaims := jwt.MapClaims{}
atClaims["authorization"] = true
atClaims["access_uuid"] = td.AccessUuid
atClaims["user_id"] = userId
atClaims["exp"] = td.AtExp
at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
td.AccessToken, err = at.SignedString([]byte(os.Getenv("ACCESS_SECRET")))
if err != nil {
return nil, err
}
td.RefreshUuid = uuid.NewV4().String()
td.RtExp = time.Now().Add(time.Hour * 24 * 7).Unix()
rfClaims := jwt.MapClaims{}
rfClaims["refresh_uuid"] = td.RefreshUuid
rfClaims["exp"] = td.RtExp
fClaims["user_id"] = userId
ft := jwt.NewWithClaims(jwt.SigningMethodHS256, rfClaims)
td.RefreshToken, err = ft.SignedString([]byte(os.Getenv("REFRESH_SECRET")))
if err != nil {
return nil, err
}
return td, nil
}
func ExtractToken(r *http.Request) string {
bearToken := r.Header.Get("authorization")
tokenString := strings.Split(bearToken, " ")
fmt.Println("Bear Token", bearToken)// tried to debug here and its not empty
if len(tokenString) == 2 {
return tokenString[1]
}
return ""
}
func VerifyToken(r *http.Request) (*jwt.Token, error) {
tokenString := ExtractToken(r)
fmt.Println(tokenString)//tried to debug here and is not empty
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
//Make sure that the token method conform to "SigningMethodHMAC"
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(os.Getenv("ACCESS_SECRET")), nil
})
if err != nil {
return nil, err
}
return token, nil
}

Using Colly framework I can't login to the Evernote account

I am using colly framework for scraping the website. Am trying to login the Evernote account for scraping some things. But I can't go through it. I used "username" and "password" titles for giving the credentials. Is this the right way ?.
Thank you in advance.
package main
import (
"log"
"github.com/gocolly/colly"
)
func main() {
// create a new collector
c := colly.NewCollector()
// authenticate
err := c.Post("https://www.evernote.com/Login.action",
map[string]string{"username":
"XXXXXX#XXX.com", "password": "*********"})
if err != nil {
log.Fatal("Error : ",err)
}
// attach callbacks after login
c.OnResponse(func(r *colly.Response) {
log.Println("response received", r.StatusCode)
})
// start scraping
c.Visit("https://www.evernote.com/")
}
You should try to mimic the browser behavior, take a look at this implementation, I've added comments on each step:
package evernote
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strings"
)
const (
evernoteLoginURL = "https://www.evernote.com/Login.action"
)
var (
evernoteJSParamsExpr = regexp.MustCompile(`document.getElementById\("(.*)"\).value = "(.*)"`)
evernoteRedirectExpr = regexp.MustCompile(`Redirecting to <a href="(.*)">`)
errNoMatches = errors.New("No matches")
errRedirectURL = errors.New("Redirect URL not found")
)
// EvernoteClient wraps all methods required to interact with the website.
type EvernoteClient struct {
Username string
Password string
httpClient *http.Client
// These parameters persist during the login process:
hpts string
hptsh string
}
// NewEvernoteClient initializes a new Evernote client.
func NewEvernoteClient(username, password string) *EvernoteClient {
// Allocate a new cookie jar to mimic the browser behavior:
cookieJar, _ := cookiejar.New(nil)
// Fill up basic data:
c := &EvernoteClient{
Username: username,
Password: password,
}
// When initializing the http.Client, copy default values from http.DefaultClient
// Pass a pointer to the cookie jar that was created earlier:
c.httpClient = &http.Client{
Transport: http.DefaultTransport,
CheckRedirect: http.DefaultClient.CheckRedirect,
Jar: cookieJar,
Timeout: http.DefaultClient.Timeout,
}
return c
}
func (e *EvernoteClient) extractJSParams(body []byte) (err error) {
matches := evernoteJSParamsExpr.FindAllSubmatch(body, -1)
if len(matches) == 0 {
return errNoMatches
}
for _, submatches := range matches {
if len(submatches) < 3 {
err = errNoMatches
break
}
key := submatches[1]
val := submatches[2]
if bytes.Compare(key, hptsKey) == 0 {
e.hpts = string(val)
}
if bytes.Compare(key, hptshKey) == 0 {
e.hptsh = string(val)
}
}
return nil
}
// Login handles the login action.
func (e *EvernoteClient) Login() error {
// First step: fetch the login page as a browser visitor would do:
res, err := e.httpClient.Get(evernoteLoginURL)
if err != nil {
return err
}
if res.Body == nil {
return errors.New("No response body")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
err = e.extractJSParams(body)
if err != nil {
return err
}
// Second step: we have extracted the "hpts" and "hptsh" parameters
// We send a request using only the username and setting "evaluateUsername":
values := &url.Values{}
values.Set("username", e.Username)
values.Set("evaluateUsername", "")
values.Set("analyticsLoginOrigin", "login_action")
values.Set("clipperFlow", "false")
values.Set("showSwitchService", "true")
values.Set("hpts", e.hpts)
values.Set("hptsh", e.hptsh)
rawValues := values.Encode()
req, err := http.NewRequest(http.MethodPost, evernoteLoginURL, bytes.NewBufferString(rawValues))
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("x-requested-with", "XMLHttpRequest")
req.Header.Set("referer", evernoteLoginURL)
res, err = e.httpClient.Do(req)
if err != nil {
return err
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return err
}
bodyStr := string(body)
if !strings.Contains(bodyStr, `"usePasswordAuth":true`) {
return errors.New("Password auth not enabled")
}
// Third step: do the final request, append password to form data:
values.Del("evaluateUsername")
values.Set("password", e.Password)
values.Set("login", "Sign in")
rawValues = values.Encode()
req, err = http.NewRequest(http.MethodPost, evernoteLoginURL, bytes.NewBufferString(rawValues))
if err != nil {
return err
}
req.Header.Set("Accept", "text/html")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("x-requested-with", "XMLHttpRequest")
req.Header.Set("referer", evernoteLoginURL)
res, err = e.httpClient.Do(req)
if err != nil {
return err
}
// Check the body in order to find the redirect URL:
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return err
}
bodyStr = string(body)
matches := evernoteRedirectExpr.FindAllStringSubmatch(bodyStr, -1)
if len(matches) == 0 {
return errRedirectURL
}
m := matches[0]
if len(m) < 2 {
return errRedirectURL
}
redirectURL := m[1]
fmt.Println("Login is ok, redirect URL:", redirectURL)
return nil
}
After you successfully get the redirect URL, you should be able to send authenticated requests as long as you keep using the HTTP client that was used for the login process, the cookie jar plays a very important role here.
To call this code use:
func main() {
evernoteClient := NewEvernoteClient("user#company", "password")
err := evernoteClient.Login()
if err != nil {
panic(err)
}
}

Go's JWT token expires when I compile new code

I am working on a SAAS based product which is built in Angular5 at front end. It uses Go's rest APIs to connect to DB and all back end functionality. I am using JWT token to authenticate the users on this system.
On the back end, I am using Gin framework for API routing and response handling.
The problem I am facing is that when ever I compile latest code on server. The token expires and it asks me to login again in order to generate new token.
The code I am using to generate JWT is given below:
package main
import (
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/contrib/sessions"
)
func CreateToken(user models.User, c *gin.Context) (string, error){
var ip, userAgent string
keyError := config.InitKeys()
if keyError != nil{
return "", keyError
}
if values, _ := c.Request.Header["Ip"]; len(values) > 0 {
ip = values[0]
}
if values, _ := c.Request.Header["User-Agent"]; len(values) > 0{
userAgent = values[0]
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.MapClaims{
"email": user.EmailId,
"exp": time.Now().Add(time.Hour * 8).Unix(),
"role": user.Role,
"name": user.FirstName+" "+user.LastName,
"ip": ip,
"user_agent": userAgent,
"id": user.Id,
})
config.CurrentUserId = user.Id
models.CurrentUser = user
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte(config.SignKey))
return tokenString, err
}
And code to compare it with the token that is being sent in the header from front end is:
if values, _ := c.Request.Header["Authorization"]; len(values) > 0 {
bearer := strings.Split(c.Request.Header["Authorization"][0], "Bearer")
bearerToken := strings.TrimSpace(bearer[1])
_, err := merchantDb.GetSession(bson.M{"token": bearerToken})
if err != nil{
errMsg := "Failed: Unauthorized Access."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
nil,
}
controllers.GetResponse(c, response)
c.Abort()
}else{
var ip, userAgent string
var ipCheck, userAgentCheck bool
if values, _ := c.Request.Header["Ip"]; len(values) > 0 {
ip = values[0]
}
if values, _ := c.Request.Header["User-Agent"]; len(values) > 0{
userAgent = values[0]
}
token, err := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {
return config.SignKey, nil
})
if len (token.Claims.(jwt.MapClaims)) > 0{
for key, claim := range token.Claims.(jwt.MapClaims) {
if key == "ip" {
if claim == ip{
ipCheck = true
}
}
if key == "user_agent"{
if claim == userAgent{
userAgentCheck = true
}
}
if key == "role"{
role = claim.(string)
}
if key == "id"{
userId = claim.(float64)
}
if key == "name"{
userName = claim.(string)
}
}
}
merchantDatabase["userid"] = userId
merchantDatabase["role"] = role
merchantDatabase["username"] = userName
c.Keys = merchantDatabase
if err == nil && token.Valid && ipCheck == true && userAgentCheck == true {
c.Next()
} else {
errMsg := "Failed: Invalid Token."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
nil,
}
controllers.GetResponse(c, response)
c.Abort()
}
}
}else{
errMsg := "Failed: Unauthorized Access."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
nil,
}
controllers.GetResponse(c, response)
c.Abort()
}
This issue is consuming a lot of time. If issue is known to anyone, Please reply to this post.
Thanks!
I suspect, there is something wrong with your session
_, err := merchantDb.GetSession(bson.M{"token": bearerToken})
or something else, as you didn't share the full code. Perhaps, your SigningKeys are not consistent between the builds.
I wrote a small test for you to prove that jwt tokens don't expire between go builds
package main
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"time"
)
func CreateToken() (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.MapClaims{
"email": "test#email.com",
"exp": time.Now().Add(time.Hour * 240).Unix(),
//"exp": time.Now().Add(-time.Hour * 8).Unix(),
"role": "test role",
"name": "test name",
"ip": "1.1.1.1",
"user_agent": "test agent",
"id": "123",
})
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte("AllYourBase"))
return tokenString, err
}
func main() {
//tokenString,_ := CreateToken()
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAZW1haWwuY29tIiwiZXhwIjoxNTIzNjAwOTM1LCJpZCI6IjEyMyIsImlwIjoiMS4xLjEuMSIsIm5hbWUiOiJ0ZXN0IG5hbWUiLCJyb2xlIjoidGVzdCByb2xlIiwidXNlcl9hZ2VudCI6InRlc3QgYWdlbnQifQ.UCD3P5-ua3qgTvy_-7hmHEVPPZwFCbhmRJNqndBwtes"
token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("AllYourBase"), nil
})
fmt.Println(token)
fmt.Println(token.Valid)
}
As you can check, the tokenString will be valid for the next 10 days wherever you run this code

How to send email through Gmail Go SDK?

I'm trying to send a new email through the gmail package . However the Message type which is required by the send method is poorly documented. Most of the fields seem used to actually parse/read emails. The only field which makes sense (at some degree) for the send method is Payload of type MessagePart though I can't figure it out how to generate the MessagePartBody as it seems to be a kind of mime type. Below is the code I have so far.
func (em *Email) SendMessage(cl *Client) error {
config.ClientId = cl.Username
config.ClientSecret = cl.Password
t := &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
}
var tk oauth.Token
err := json.Unmarshal([]byte(cl.Meta), &tk)
t.Token = &tk
if err != nil {
log.Errorf("meta %v, err %v", cl.Meta, err)
return err
}
gmailService, err := gmail.New(t.Client())
if err != nil {
log.Error(err)
return err
}
p := gmail.MessagePart{}
p.Headers = append(p.Headers, &gmail.MessagePartHeader{
Name: "From",
Value: em.FromEmail,
})
p.Headers = append(p.Headers, &gmail.MessagePartHeader{
Name: "To",
Value: em.ToEmail,
})
p.Headers = append(p.Headers, &gmail.MessagePartHeader{
Name: "Subject",
Value: em.Subject,
})
emsg := base64.StdEncoding.EncodeToString(em.Message)
log.Info(emsg)
msg := gmail.Message{
Payload: &p,
Raw: "",
}
_, err = gmailService.Users.Messages.Send("me", &msg).Do()
if err != nil {
log.Error(err)
return err
}
return err
}
The "REST" API is even more confusing. It requires an uploadType param (WTF to upload) and a raw field which I guess is the raw message which requires a format provided by messages.get. Why would you send a message from your inbox which literally would be a 'resend' as your are on the receipt list ? Am I the only one who thinks this API(or at least the documentation) is just crap ?
It was a bit tricky but here is how you can send emails through the GMAIL API
import(
"code.google.com/p/goauth2/oauth"
"code.google.com/p/google-api-go-client/gmail/v1"
log "github.com/golang/glog"
"encoding/base64"
"encoding/json"
"net/mail"
"strings"
)
type Email struct {
FromName, FromEmail, ToName, ToEmail, Subject string
Message string
}
func (em *Email) SendMessage(cl *Client) error {
config.ClientId = cl.Username //oauth clientID
config.ClientSecret = cl.Password //oauth client secret
t := &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
}
var tk oauth.Token
err := json.Unmarshal([]byte(cl.Meta), &tk)
t.Token = &tk
if err != nil {
log.Errorf("meta %v, err %v", cl.Meta, err)
return err
}
gmailService, err := gmail.New(t.Client())
if err != nil {
log.Error(err)
return err
}
from := mail.Address{em.FromName, em.FromEmail}
to := mail.Address{em.ToName, em.ToEmail}
header := make(map[string]string)
header["From"] = from.String()
header["To"] = to.String()
header["Subject"] = encodeRFC2047(em.Subject)
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/html; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"
var msg string
for k, v := range header {
msg += fmt.Sprintf("%s: %s\r\n", k, v)
}
msg += "\r\n" + em.Message
gmsg := gmail.Message{
Raw: encodeWeb64String([]byte(msg)),
}
_, err = gmailService.Users.Messages.Send("me", &gmsg).Do()
if err != nil {
log.Errorf("em %v, err %v", gmsg, err)
return err
}
return err
}
func encodeRFC2047(s string) string {
// use mail's rfc2047 to encode any string
addr := mail.Address{s, ""}
return strings.Trim(addr.String(), " <>")
}
func encodeWeb64String(b []byte) string {
s := base64.URLEncoding.EncodeToString(b)
var i = len(s) - 1
for s[i] == '=' {
i--
}
return s[0 : i+1]
}
Similar to #hey 's answer, but I tidied it up, and allowed the email to put newlines in the email body through \n and show up correctly on the email client. Also, #hey is not using the new supported Gmail API. Here is the final code:
import (
"encoding/base64"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
"encoding/json"
"net/mail"
)
type Email struct {
FromName string
FromEmail string
ToName string
ToEmail string
Subject string
Message string
}
func (em *Email) sendMailFromEmail() error {
b, err := ioutil.ReadFile("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.GmailSendScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
cl := getClientMail(config)
gmailService, err := gmail.New(cl)
if err != nil {
log.Fatalf("Unable to retrieve Gmail client: %v", err)
}
from := mail.Address{em.FromName, em.FromEmail}
to := mail.Address{em.ToName, em.ToEmail}
header := make(map[string]string)
header["From"] = from.String()
header["To"] = to.String()
header["Subject"] = em.Subject
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/plain; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"
var msg string
for k, v := range header {
msg += fmt.Sprintf("%s: %s\r\n", k, v)
}
msg += "\r\n" + em.Message
gmsg := gmail.Message{
Raw: base64.RawURLEncoding.EncodeToString([]byte(msg)),
}
_, err = gmailService.Users.Messages.Send("me", &gmsg).Do()
if err != nil {
log.Printf("em %v, err %v", gmsg, err)
return err
}
return err
}
I did not include the following functions: getClient, getTokenFromWeb, tokenFromFile, and saveToken. You can find them, and learn how to enable the Gmail API through this tutorial by Google.

Resources