我正在尝试使用Gmail的API发送电子邮件,但我一直收到错误:
无法发送googleapi:错误400:错误请求,failedPrecondition 退出状态1
我在console.developers.google.com页面中为此创建了一个服务帐户,并下载了私有json文件。将其重命名为GmailService.json,并在文档中搜索了如何实现它。从我可以告诉的一切都有效,除非它在代码结束时到达send方法。服务电子邮件不允许我发送电子邮件或邮件格式错误?
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\r\n" +
"To: recipient@gmail.com\r\n" +
"Subject: Testing testing \r\n" +
"\r\nThis 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)
}
}