Skip to main content

Go SDK

The simpleemailapi-go package provides a fully typed, high-performance SDK for Go applications with real-time event streaming.
Language: Go 1.21+
Transport: HTTP/2 via Connect RPC

Installation

go get github.com/emailapi/sdk-go

Usage

Initialize the client with your API key and use the client.Send method.
package main

import (
    "context"
    "fmt"
    "log"

    emailapi "github.com/emailapi/sdk-go"
    v1 "github.com/emailapi/sdk-go/gen/v1"
)

func main() {
    client := emailapi.NewClient("sea_live_...")

    resp, err := client.Send(context.Background(), &v1.SendEmailRequest{
        From:    "[email protected]",
        To:      []string{"[email protected]"},
        Subject: "Hello!",
        Body:    "Thanks for signing up.",
        Html:    "<p>Thanks for signing up.</p>",
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Email ID:", resp.Msg.Id)
}
The From address must belong to a domain you have verified.

Client Configuration

The NewClient function accepts optional configuration:
// Default usage
client := emailapi.NewClient("sea_live_...")

// With custom options
client := emailapi.NewClient("sea_live_...",
    emailapi.WithBaseURL("https://custom-endpoint.com"),
    emailapi.WithHTTPClient(customHTTPClient),
)
apiKey
string
required
Your API Key, starting with sea_live_.
WithBaseURL
ClientOption
Sets a custom API endpoint. Defaults to https://api.simpleemailapi.dev.
WithHTTPClient
ClientOption
Uses a custom http.Client for requests.

SendEmailRequest Fields

From
string
required
Sender email address. Must be from a verified domain.
To
[]string
required
List of primary recipient email addresses.
Subject
string
required
Email subject line.
Body
string
Plain text content of the email.
Html
string
HTML content of the email.
Cc
[]string
List of CC recipient email addresses.
Bcc
[]string
List of BCC recipient email addresses.
Attachments
[]*Attachment
List of files to attach.
ReplyTo
string
Reply to a previous email using its Id from our response. We automatically resolve threading headers.
InReplyTo
string
Raw Message-ID for threading (advanced). Use ReplyTo for simpler threading with our email IDs.
References
[]string
List of message IDs for threading context (advanced).
Metadata
map[string]string
Custom key-value metadata returned in webhooks.
All emails are queued for reliable delivery with automatic retries. Use webhooks or event streaming to track delivery status.

Real-time Event Streaming

Stream email events with typed callbacks using OnReceive:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

client.OnReceive(ctx, emailapi.EventHandlers{
    OnDelivered: func(e *v1.EmailDeliveredEvent) {
        log.Println("Delivered to:", e.Recipients)
    },
    OnReplied: func(e *v1.EmailRepliedEvent) {
        log.Println("Reply from:", e.From)
    },
    OnBounced: func(e *v1.EmailBouncedEvent) {
        log.Println("Bounced:", e.BounceType, e.Recipients)
    },
    OnError: func(err error) {
        log.Println("Stream error:", err)
    },
})
The stream runs in a background goroutine and automatically reconnects with exponential backoff.

Available Event Handlers

HandlerDescription
OnSentEmail accepted for delivery
OnDeliveredEmail delivered to recipient’s mailbox
OnBouncedEmail bounced (hard or soft)
OnComplainedRecipient marked email as spam
OnRejectedEmail rejected before sending
OnDelayedEmail delivery delayed
OnRepliedReply received to a sent email
OnFailedEmail sending failed permanently
OnErrorStream error occurred

Error Handling

The SDK provides structured error handling with typed error codes:
resp, err := client.Send(ctx, req)
if err != nil {
    if e := emailapi.ParseError(err); e != nil {
        switch {
        case e.Is(emailapi.ErrCodeDomainNotVerified):
            log.Println("Please verify your domain first")
        case e.IsCategory(emailapi.CategoryValidation):
            log.Println("Validation error on field:", e.Field)
        case e.IsCategory(emailapi.CategoryRateLimit):
            log.Println("Rate limited, retry later")
        default:
            log.Println("Error:", e.Message)
        }
    }
}

Error Categories

CategoryRangeDescription
CategoryAuth1xxAuthentication errors
CategoryAuthz2xxAuthorization errors
CategoryValidation3xxValidation errors
CategoryNotFound4xxResource not found
CategoryDomain5xxDomain verification errors
CategoryRateLimit6xxRate/usage limit errors
CategoryInternal9xxInternal server errors

Advanced Usage

Access underlying service clients for domain management:
// Domain management
domains, err := client.Domains.ListDomains(ctx, 
    connect.NewRequest(&v1.ListDomainsRequest{}))

// Direct email service access
resp, err := client.Emails.SendEmail(ctx, 
    connect.NewRequest(&v1.SendEmailRequest{...}))