Send Email with Go


Posted on

Go GopherLike many developers, I like to check out new technologies and languages. That’s why I recently started learning Go. My regular approach to learning is to build something. For Go, I decided I would learn by creating a SendGrid-Go library.

Initially, I searched for an SMTP client that would allow everything SendGrid’s SMTP API supports, but I was not very lucky. Therefore, as a prerequisite to a Go library, I wrote smtpmail for Go. The SendGrid-Go library is built on top of my first library and extends it so it would support the SendGrid Web API, too.

So, on with the example. It’s simple to use. Assuming you’ve already installed Go, first, you will need to download and install the library (and its dependencies) by running the following command:

go get github.com/sendgrid/sendgrid-go

Now you’re ready to add email to your Go script:

import (
    "fmt"
    "net/mail"
    "github.com/sendgrid/sendgrid-go"
)

func main() {
    sg := sendgrid.NewSendGridClient("sendgrid_user", "sendgrid_key")
    message := sendgrid.NewMail()
    message.AddTo("yamil@sendgrid.com")
    message.AddSubject("My first email!")
    message.AddText("Sending Email from Go using SendGrid")
    message.AddFrom("yamil.asusta@sendgrid.com")
    if r := sg.Send(message); r == nil {
        fmt.Println("Email sent!")
    } else {
        fmt.Println(r)
    }
}

In order to initialize the client, you must pass your SendGrid credentials, so change those within the code fragment above. Afterwards, just create a message object and set some properties like destination and sender. Then use the client to send the message. Magic. If everything went according to plan, you won’t receive an error.

There are three ways to send emails using this library:

  1. The SendAPI method will use the Web API
  2. The SendSMTP method will use SMTP as its transport
  3. The Send method will try to use SendAPI, but fallback to SendSMTP if the first fails

There is a more in-depth documentation found in the GitHub repository.

Feel free to give me a shout if something blew up or just to say “hi!” I’m also going to Gophercon 2014, so if you are going, I would love to meet up.


Puerto Rican and hackNY '13 fellow. Always looking to hack/experiment something new. You can follow me @elbuo8

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>