我对 gmail api 的新 NewService 功能有疑问。如果我使用已弃用的 gmail.New() 一切正常。使用 NewService() 我得到invalid memory address or nil pointer dereference
我的实现如下
type MailData struct {
To string
Name string
Subject string
Content template.HTML
}
func doSend(msg *gmail.Message, srv *gmail.Service) error {
_, err := srv.Users.Messages.Send("me", msg).Do()
if err != nil {
return err
}
return nil
}
func ComposeMessage(m models.MailData) *gmail.Message {
var gmailMessage gmail.Message
from := mail.Address{Name: "Sender", Address: os.Getenv("MAIL_FROM")}
replyTo := os.Getenv("MAIL_REPLYTO")
to := mail.Address{Name: m.Name, Address: m.To}
header := make(map[string]string)
header["From"] = from.String()
header["Reply-To"] = replyTo
header["To"] = to.String()
header["Subject"] = m.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" + string(m.Content)
gmailMessage.Raw = base64.RawURLEncoding.EncodeToString([]byte(msg))
return &gmailMessage
}
使用旧的 gmail.New() 有效,但它指出该功能已弃用,因此我需要将其更改为新的 gmail.NewService。虽然像下面这样实现它是行不通的
func sendGMail(m models.MailData) error {
credentials := "../gmail_credentials.json"
ctx := context.Background()
srv, err := gmail.NewService(
ctx,
option.WithCredentialsFile(credentials),
option.WithScopes("https://www.googleapis.com/auth/gmail.send"),
)
if err != nil {
return errors.New(fmt.Sprintf("unable to retrieve gmail client: %s", err))
}
// Create message
gMessage := ComposeMessage(m)
if err := doSend(gMessage, srv); err != nil {
return errors.New(fmt.Sprintf("could not send mail: %s", err))
}
fmt.Println("Email sent")
return nil
}
守着星空守着你
相关分类