Home  >  Article  >  Backend Development  >  How to Send Emails Effectively with the Gmail Go SDK: A Step-by-Step Guide

How to Send Emails Effectively with the Gmail Go SDK: A Step-by-Step Guide

Susan Sarandon
Susan SarandonOriginal
2024-10-28 08:08:30997browse

How to Send Emails Effectively with the Gmail Go SDK: A Step-by-Step Guide

Sending Emails with Gmail Go SDK

Sending emails through the Gmail Go SDK can be challenging, as the Message type required by the send method has limited documentation. However, with the following code, you can effectively send emails using the service:

<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 := &amp;oauth.Transport{
        Config:    config,
        Transport: http.DefaultTransport,
    }
    var tk oauth.Token
    err := json.Unmarshal([]byte(cl.Meta), &amp;tk)
    t.Token = &amp;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", &amp;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>

This improved code:

  • Constructs the email header using net/mail for enhanced MIME compliance.
  • Encodes the email using base64 and adds it to the Raw field of the Message type.
  • Uses mail.Address to correctly format From and To addresses.

The above is the detailed content of How to Send Emails Effectively with the Gmail Go SDK: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn