I'm attempting to send email using Gmail's API but I keep getting the error:
Unable to send googleapi: Error 400: Bad Request, failedPrecondition exit status 1
I created a service account for this in the console.developers.google.com page and downloaded the private json file. Renamed it GmailService.json and searched through the docs on how to implement it. From what I can tell everything works except when it gets to the send method at the end of the code. Either the service email doesn't allow me to send email or the message is formatted wrong?
package main
import "golang.org/x/oauth2"
import "golang.org/x/oauth2/google"
import "google.golang.org/api/gmail/v1"
import "io/ioutil"
import "log"
import "encoding/base64"
import "strings"
func main() {
data, err := ioutil.ReadFile("GmailService.json")
if err != nil {
log.Fatal(err)
}
conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/gmail.send")
if err != nil {
log.Fatalf("conf: %v", err)
}
client := conf.Client(oauth2.NoContext)
gmailService, err := gmail.New(client)
if err != nil {
log.Fatalf("gmailService: %v", err)
}
var message gmail.Message
messageStr := []byte("From: service-email@gmail.com
" +
"To: recipient@gmail.com
" +
"Subject: Testing testing
" +
"
This message was created with an api")
message.Raw = base64.StdEncoding.EncodeToString(messageStr)
message.Raw = strings.Replace(message.Raw, "/", "_", -1)
message.Raw = strings.Replace(message.Raw, "+", "-", -1)
message.Raw = strings.Replace(message.Raw, "=", "", -1)
_, err = gmailService.Users.Messages.Send("me", &message).Do()
if err != nil {
log.Fatalf("Unable to send %v", err)
}
}