使用 Gmail Go SDK 发送电子邮件
通过 Gmail Go SDK 发送电子邮件可能具有挑战性,因为发送方法所需的消息类型文档有限。但是,通过以下代码,您可以使用该服务有效地发送电子邮件:
<code class="go">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] }</code>
此改进的代码:
以上是如何使用 Gmail Go SDK 有效发送电子邮件:分步指南的详细内容。更多信息请关注PHP中文网其他相关文章!