Skip to content

Go quickstart

Use the Go standard library to send with HTTP or SMTP.

  1. A Comail account with an enrolled, DNS-verified sending domain. Sign up if you need an account.
  2. Your account ID (DID) and an API key for your sending domain. Open API keys in the Builders console to create a key. Save it when it appears. To replace a lost key, follow the API key guide.
  3. Go 1.21 or newer (go version).
  4. A real recipient address you can check. Replace example.com in the examples below; the relay rejects IANA example domains with 422 INVALID_RECIPIENT_DOMAIN on HTTP and 556 5.1.10 on SMTP.

Save as send.go:

package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
type sendRequest struct {
From string `json:"from"`
To string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text,omitempty"`
HTML string `json:"html,omitempty"`
ReplyTo string `json:"replyTo,omitempty"`
Category string `json:"category,omitempty"`
}
type recipientResult struct {
Recipient string `json:"recipient"`
MessageID int64 `json:"messageId,omitempty"`
Error string `json:"error,omitempty"`
}
type sendResponse struct {
Accepted []recipientResult `json:"accepted"`
Rejected []recipientResult `json:"rejected"`
}
type sendError struct {
Code string `json:"code"`
Message string `json:"error"`
Rejected []recipientResult `json:"rejected"`
}
func main() {
did := os.Getenv("COMAIL_DID")
apiKey := os.Getenv("COMAIL_API_KEY")
if did == "" || apiKey == "" {
fmt.Fprintln(os.Stderr, "Set COMAIL_DID and COMAIL_API_KEY")
os.Exit(1)
}
body, err := json.Marshal(sendRequest{
From: "you@yourdomain.com",
To: "alice@example.com",
Subject: "Hello from comail",
Text: "If you can read this, the API key works.",
})
if err != nil {
fmt.Fprintln(os.Stderr, "marshal:", err)
os.Exit(1)
}
req, err := http.NewRequest("POST", "https://smtp.atmos.email/v1/send", bytes.NewReader(body))
if err != nil {
fmt.Fprintln(os.Stderr, "new request:", err)
os.Exit(1)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Atmos-DID", did)
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
fmt.Fprintln(os.Stderr, "send:", err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
var e sendError
decodeErr := json.NewDecoder(resp.Body).Decode(&e)
if decodeErr != nil {
fmt.Fprintf(os.Stderr, "send failed: HTTP %d\n", resp.StatusCode)
} else if len(e.Rejected) > 0 {
fmt.Fprintf(os.Stderr, "send failed: HTTP %d\n", resp.StatusCode)
for _, r := range e.Rejected {
fmt.Fprintf(os.Stderr, " %s: %s\n", r.Recipient, r.Error)
}
} else {
fmt.Fprintf(os.Stderr, "send failed: %d %s: %s\n", resp.StatusCode, e.Code, e.Message)
}
os.Exit(1)
}
var result sendResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
fmt.Fprintln(os.Stderr, "decode:", err)
os.Exit(1)
}
fmt.Printf("accepted: %d\n", len(result.Accepted))
fmt.Printf("rejected: %d\n", len(result.Rejected))
for _, r := range result.Accepted {
fmt.Printf(" -> %s (messageId: %d)\n", r.Recipient, r.MessageID)
}
}

In send.go, replace you@yourdomain.com with your sending address and alice@example.com with your own recipient address. Set your DID and API key in the shell, then run the example.

Terminal window
export COMAIL_DID=did:plc:your-did-here
export COMAIL_API_KEY=atmos_your-api-key
go run send.go

Expected output when the relay accepts the message:

accepted: 1
rejected: 0
-> alice@example.com (messageId: 12345)

Look for your recipient and a messageId in accepted. This means the relay has queued the message. Check your account or the Events API for delivery status. If the domain is in its first 14 days of sending, check the spam folder too.

net/smtp ships in the standard library and uses STARTTLS on port 587 with SASL PLAIN.

Replace you@yourdomain.com and alice@example.com with your enrolled sender address and a real recipient address, and run with COMAIL_DID and COMAIL_API_KEY set in your environment:

package main
import (
"fmt"
"net/smtp"
"os"
"strings"
)
func main() {
did := os.Getenv("COMAIL_DID")
apiKey := os.Getenv("COMAIL_API_KEY")
if did == "" || apiKey == "" {
fmt.Fprintln(os.Stderr, "Set COMAIL_DID and COMAIL_API_KEY")
os.Exit(1)
}
// smtp.PlainAuth handles the SASL PLAIN handshake. The first
// argument (identity) is empty per RFC 4616. The username is
// your DID or your enrolled sending domain.
auth := smtp.PlainAuth("", did, apiKey, "smtp.atmos.email")
from := "you@yourdomain.com"
to := []string{"alice@example.com"}
msg := strings.Join([]string{
"From: " + from,
"To: " + to[0],
"Subject: Hello from comail (SMTP)",
"",
"If you can read this, SMTP submission works.",
}, "\r\n")
// SendMail handles the connect, STARTTLS, AUTH, MAIL FROM,
// RCPT TO, DATA, and QUIT sequence in one call.
if err := smtp.SendMail("smtp.atmos.email:587", auth, from, to, []byte(msg)); err != nil {
fmt.Fprintln(os.Stderr, "send:", err)
os.Exit(1)
}
fmt.Println("sent")
}

Run with the same environment variables:

Terminal window
go run send.go

When smtp.SendMail returns nil (250 OK from the relay) and prints sent, the relay has synced the message to disk and queued it for delivery.

Details for the SMTP path:

  • Use port 587 with STARTTLS. Port 465 (implicit TLS) is not available.
  • net/smtp is the standard library’s minimal SMTP client and is frozen in Go 1.x. If you need extra message-building features, use a library such as github.com/wneessen/go-mail.
  • The username for PlainAuth can be either your DID (did:plc:…) or your enrolled sending domain (yourdomain.com). Use the sending domain if your configuration format cannot pass colons in a username.

For a project where you send from multiple places:

internal/comail/comail.go
package comail
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"time"
)
type Client struct {
did string
apiKey string
http *http.Client
}
type Mail struct {
From string `json:"from"`
To []string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text,omitempty"`
HTML string `json:"html,omitempty"`
ReplyTo string `json:"replyTo,omitempty"`
Category string `json:"category,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
}
type Recipient struct {
Recipient string `json:"recipient"`
MessageID int64 `json:"messageId,omitempty"`
Error string `json:"error,omitempty"`
}
type Response struct {
Accepted []Recipient `json:"accepted"`
Rejected []Recipient `json:"rejected"`
}
type APIError struct {
Status int
Code string `json:"code"`
Message string `json:"error"`
Rejected []Recipient `json:"rejected"`
}
func (e *APIError) Error() string {
if len(e.Rejected) > 0 {
return fmt.Sprintf("comail %d: all recipients rejected", e.Status)
}
if e.Code == "" && e.Message == "" {
return fmt.Sprintf("comail HTTP %d", e.Status)
}
return fmt.Sprintf("comail %d %s: %s", e.Status, e.Code, e.Message)
}
// NewFromEnv reads COMAIL_DID + COMAIL_API_KEY from the environment.
// Returns an error if either is missing so callers can fail fast at
// startup instead of on first send.
func NewFromEnv() (*Client, error) {
did := os.Getenv("COMAIL_DID")
apiKey := os.Getenv("COMAIL_API_KEY")
if did == "" || apiKey == "" {
return nil, errors.New("COMAIL_DID and COMAIL_API_KEY must be set")
}
return &Client{
did: did,
apiKey: apiKey,
http: &http.Client{Timeout: 15 * time.Second},
}, nil
}
func (c *Client) Send(m Mail) (*Response, error) {
body, err := json.Marshal(m)
if err != nil {
return nil, fmt.Errorf("marshal: %w", err)
}
req, err := http.NewRequest("POST", "https://smtp.atmos.email/v1/send", bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("new request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Atmos-DID", c.did)
req.Header.Set("Authorization", "Bearer "+c.apiKey)
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("do: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
raw, _ := io.ReadAll(resp.Body)
var apiErr APIError
_ = json.Unmarshal(raw, &apiErr)
apiErr.Status = resp.StatusCode
return nil, &apiErr
}
var out Response
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
return &out, nil
}

Usage:

client, err := comail.NewFromEnv()
if err != nil {
log.Fatal(err)
}
result, err := client.Send(comail.Mail{
From: "auth@yourdomain.com",
To: []string{"alice@example.com"},
Subject: "Sign-in link",
Text: "https://your-app.com/auth?token=abc123",
Category: "login-link",
})
var apiErr *comail.APIError
switch {
case errors.As(err, &apiErr):
switch apiErr.Code {
case "RATE_LIMITED":
// warming or per-member cap; back off
case "DOMAIN_MISMATCH":
// from: domain isn't enrolled
case "SUSPENDED", "PENDING":
// account-level issue; check /account
default:
log.Printf("send: %s", apiErr)
}
case err != nil:
log.Fatal(err)
default:
log.Printf("accepted: %d, rejected: %d", len(result.Accepted), len(result.Rejected))
}

See HTTP Send API for the full error code table.

To accepts up to 50 addresses per request. In a multi-recipient call, an HTTP 200 response lists the queued recipients in Accepted and any failures in Rejected. If every recipient fails and the response has a list of failures, the client puts that list on the APIError as Rejected.

Check each rejection before retrying. Send again only to addresses that failed temporarily.

result, err := client.Send(comail.Mail{
From: "news@yourdomain.com",
To: []string{"alice@example.com", "bob@example.com"},
Subject: "Acme weekly",
HTML: "<p>Latest updates...</p>",
Category: "bulk",
})
if err != nil {
log.Fatal(err)
}
for _, r := range result.Accepted {
log.Printf("OK %s: %d", r.Recipient, r.MessageID)
}
for _, r := range result.Rejected {
log.Printf("ERR %s: %s", r.Recipient, r.Error)
}

The relay returns messageId as a JSON number (Go int64). Do not type it as a string in your structs unless you convert it explicitly.

Back to docs