Go
SpacePost ist eine schlichte JSON-API, deshalb reicht die Standardbibliothek.
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"`}
func (e apiError) Error() string { return fmt.Sprintf("%d %s: %s", e.StatusCode, e.Name, e.Message) }
var client = &http.Client{Timeout: 15 * time.Second}
func Send(e Email, idempotencyKey string) (string, error) { payload, _ := json.Marshal(e) req, err := http.NewRequest("POST", "https://api.spacepost.dev/emails", bytes.NewReader(payload)) if err != nil { return "", err } req.Header.Set("Authorization", "Bearer "+os.Getenv("SPACEPOST_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 >= 300 { var ae apiError if err := json.NewDecoder(res.Body).Decode(&ae); err != nil { return "", fmt.Errorf("unexpected status %d", res.StatusCode) } return "", ae } var ok struct { ID string `json:"id"` } if err := json.NewDecoder(res.Body).Decode(&ok); err != nil { return "", err } return ok.ID, nil}
func main() { id, err := Send(Email{ From: "Acme <hello@acme.com>", To: []string{"delivered@test.spacepost.dev"}, Subject: "Hello from Go", HTML: "<p>It works.</p>", }, "") if err != nil { panic(err) } fmt.Println("sent", id)}SPACEPOST_API_KEY=sp_live_YOUR_API_KEY go run .