Sending Gopher Emails

So you want to send some email. And you’re using Go. Do I have some great news for you! I have done this, and you can too. We’re going to build a tool that I’ve appropriately named send-a-gopher which, unsurprisingly, sends you (well, somebody) a gopher.

This tutorial assumes you already have a SparkPost account and have created an API key. And that you’ve got Go installed on your system.

First! Pick a gopher to send

This is undoubtedly the hardest part. After careful consideration, and a quick right click, copy image address, there’s your gopher. Oh, right. We need some code too.

res, _ := http.Get(imgUrl) // get the image

Et voila! An extremely limited in-memory version of curl/wget/etc! We can now get gophers.

Second! Set up the SparkPost package

Installing the package is arguably the easiest part:

$ go get

And that’s it. Next we’ll import and configure the SparkPost package:

cfg := &gosp.Config{ApiKey: os.Getenv(“SPARKPOST_API_KEY”) 
var sp gosp.Client 

Third! Encase the gopher in code

We’ll get it from the HTTP response, wrap it up in an InlineImage and some Content, then send that off in a Transmission:


body, _ := ioutil.ReadAll(res.Body)
ctype := http.DetectContentType(body) 
filename := path.Base(imgUrl)
iimg := gosp.InlineImage{
    MIMEType: ctype,
    Filename: filename,
    B64Data:  base64.StdEncoding.EncodeToString(body),
html := fmt.Sprintf(`Here's that gopher you maybe asked for!<br/><img src="cid:%s" />`, filename)
content := gosp.Content{
    From:    *from,
    Subject: "That gopher",
    HTML:    html,
content.InlineImages = append(content.InlineImages, iimg)
tx := &gosp.Transmission{
    Content:    content,
    Recipients: []string{*to},
id, _, err := sp.Send(tx)


Last! Send, and admire your handiwork

This is the second easiest part:

$ ./send-a-gopher 
2017/11/17 15:12:30 Successfully sent nothing, but that's probably not what you 
wanted? Check out the --url option.

Er, you get the idea.

$ ./send-a-gopher --url \
 --from --to

Look at you now. With a free account and just a little bit of code, you’re sending yourself gophers. That was pretty easy, and there are more sending examples in our GitHub repository, specifically in the sparks tool, along with the complete version of the code we’ve dissected here. It even handles errors.

-Dave Gray