我现在已经为这个错误(googleapi: Error 400: Bad Request, failedPrecondition
)奋斗了大约8个小时。我写了一个简单的go程序,它为我重现了这个问题。也许熟悉Google API的人可以帮助我。
错误与此处提到的错误相同:Gmail REST API : 400 Bad Request + Failed Precondition。唯一的区别是它在Go中。我已按照步骤操作,但仍然没有运气。
我还根据How to send email through Gmail Go SDK?
更新了我的代码这两个问题都有帮助,但无法解决最新问题。我还将GOOGLE_APPLICATION_CREDENTIALS
设置为我的项目的json。
package main
import (
"encoding/base64"
"fmt"
"log"
"net/mail"
"strings"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
gmail "google.golang.org/api/gmail/v1"
)
func main() {
// Use oauth2.NoContext if there isn't a good context to pass in.
ctx := context.TODO()
client, err := google.DefaultClient(ctx, gmail.GmailSendScope)
if err != nil {
panic(err)
}
// create service
svc, err := gmail.New(client)
if err != nil {
log.Fatalf("Unable to create Gmail service: %v", err)
}
if err := SendEmail(ctx, svc, <redacted>); err != nil {
log.Fatalf("failed to send email: %v", err)
}
}
func SendEmail(ctx context.Context, svc *gmail.Service, email string) error {
from := mail.Address{"", "noreply@example.com"}
header := make(map[string]string)
header["From"] = from.String()
header["To"] = email
header["Subject"] = encodeRFC2047("Hello, Gmail!")
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" + "Hello, Gmail!"
gmsg := gmail.Message{
Raw: encodeWeb64String([]byte(msg)),
}
_, err := svc.Users.Messages.Send("me", &gmsg).Do()
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]
}
运行上面的代码会产生以下错误:
2015/12/12 22:16:46 failed to send email: googleapi: Error 400: Bad Request, failedPrecondition
答案 0 :(得分:0)
要发送邮件,您必须为From:标题(https://support.google.com/mail/answer/22370)指定有效地址。 noreply@example.com
不太可能是这样的地址,因为example.com是每个RFC 2606的仅测试域。