Send with

Send email with Go

The standard library is enough: net/http and encoding/json.

Send an email

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

type Email struct {
	From    string   `json:"from"`
	To      []string `json:"to"`
	Subject string   `json:"subject"`
	HTML    string   `json:"html,omitempty"`
	Text    string   `json:"text,omitempty"`
}

type apiError struct {
	StatusCode int    `json:"statusCode"`
	Name       string `json:"name"`
	Message    string `json:"message"`
}

var client = &http.Client{Timeout: 15 * time.Second}

func SendEmail(e Email, idempotencyKey string) (string, error) {
	payload, err := json.Marshal(e)
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", "https://robustemail.com/api/v2/emails", bytes.NewReader(payload))
	if err != nil {
		return "", err
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("ROBUSTEMAIL_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	if idempotencyKey != "" {
		req.Header.Set("Idempotency-Key", idempotencyKey)
	}

	res, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()

	if res.StatusCode >= 400 {
		var e apiError
		json.NewDecoder(res.Body).Decode(&e)
		return "", fmt.Errorf("%s: %s", e.Name, e.Message)
	}

	var ok struct {
		ID string `json:"id"`
	}
	err = json.NewDecoder(res.Body).Decode(&ok)
	return ok.ID, err
}

func main() {
	id, err := SendEmail(Email{
		From:    "Acme <hello@acme.com>",
		To:      []string{"delivered@sandbox.robustemail.dev"},
		Subject: "Welcome to Acme",
		HTML:    "<h1>Welcome!</h1>",
	}, "welcome-user-1042")
	if err != nil {
		fmt.Println("send failed:", err)
		return
	}
	fmt.Println("queued", id)
}

Next