camelmailer

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 11 Imported by: 0

README

camelmailer-go

CI Go Reference

The official Go SDK for CamelMailer — transactional email, nothing else. Zero dependencies, stdlib only.

Install

go get github.com/camelmailer/camelmailer-go

Requires Go 1.21+.

Quickstart

client := camelmailer.NewClient("cm_xxxx")

sent, err := client.Emails.Send(ctx, &camelmailer.SendEmailRequest{
	From:     camelmailer.Address{Email: "billing@acme.com"},
	To:       []camelmailer.Address{{Email: "ada@example.com"}},
	Subject:  "Your receipt",
	TextBody: "Thanks for your purchase.",
})

Self-hosted

The client defaults to the CamelMailer cloud. Point it at your own instance:

client := camelmailer.NewClient("cm_xxxx",
	camelmailer.WithBaseURL("https://mail.example.com"),
	camelmailer.WithHTTPClient(&http.Client{Timeout: 10 * time.Second}),
)

Emails

// Send with attachments, tags and metadata
sent, err := client.Emails.Send(ctx, &camelmailer.SendEmailRequest{
	From:     camelmailer.Address{Email: "billing@acme.com", Name: "Acme Billing"},
	To:       []camelmailer.Address{{Email: "ada@example.com"}},
	Subject:  "Invoice #42",
	HTMLBody: "<h1>Your invoice</h1>",
	Attachments: []camelmailer.Attachment{
		{Name: "invoice.pdf", ContentType: "application/pdf", Data: pdfBytes},
	},
	Tag:      "invoice",
	Metadata: map[string]any{"order_id": 42},
})

// Batch send — one result per entry, entries fail individually
results, err := client.Emails.SendBatch(ctx, []*camelmailer.SendEmailRequest{msg1, msg2})

// Send with a stored template
sent, err := client.Emails.SendWithTemplate(ctx, &camelmailer.SendWithTemplateRequest{
	SendEmailRequest: camelmailer.SendEmailRequest{
		From: camelmailer.Address{Email: "hello@acme.com"},
		To:   []camelmailer.Address{{Email: "ada@example.com"}},
	},
	Template:      "welcome",
	TemplateModel: map[string]any{"name": "Ada"},
})

// Read messages
email, err := client.Emails.Get(ctx, sent.MessageID)             // message + deliveries
list, err := client.Emails.List(ctx, &camelmailer.ListEmailsOptions{Tag: "invoice"})
deliveries, err := client.Emails.Deliveries(ctx, id)
opens, err := client.Emails.Opens(ctx, id)
clicks, err := client.Emails.Clicks(ctx, id)
raw, err := client.Emails.Raw(ctx, id)                           // decoded RFC 5322 bytes

Templates

tmpl, err := client.Templates.Create(ctx, &camelmailer.CreateTemplateRequest{
	Name:     "Welcome",
	Subject:  "Hello {{ name }}",
	HTMLBody: "<p>Hi {{ name }}</p>",
})
templates, err := client.Templates.List(ctx)
tmpl, err = client.Templates.Get(ctx, "welcome")
tmpl, err = client.Templates.Update(ctx, "welcome", &camelmailer.UpdateTemplateRequest{
	Subject: camelmailer.String("Hi {{ name }}!"),
})
rendered, err := client.Templates.Render(ctx, "welcome", map[string]any{"name": "Ada"})
tmpl, err = client.Templates.Archive(ctx, "welcome")

Streams

streams, err := client.Streams.List(ctx)
stream, err := client.Streams.Create(ctx, &camelmailer.CreateStreamRequest{
	Name: "Broadcasts", StreamType: "broadcast",
})
stream, err = client.Streams.Get(ctx, "broadcasts")
stream, err = client.Streams.Update(ctx, "broadcasts", &camelmailer.UpdateStreamRequest{
	Name: camelmailer.String("Newsletter"),
})
stream, err = client.Streams.Archive(ctx, "broadcasts")

Stats & bounces

stats, err := client.Stats.Get(ctx, &camelmailer.StatsOptions{From: monthStart})
queue, err := client.Stats.Deliveries(ctx)   // outbound queue depth per domain
bounces, err := client.Bounces.List(ctx, nil)
bounce, err := client.Bounces.Get(ctx, id)

DMARC

summary, err := client.DMARC.Summary(ctx, &camelmailer.DMARCSummaryOptions{Domain: "acme.com"})
reports, err := client.DMARC.Reports(ctx, nil)
report, err := client.DMARC.Report(ctx, reports.Reports[0].ID)

Error handling

Every API failure is a typed *camelmailer.APIError with the stable error code and HTTP status:

sent, err := client.Emails.Send(ctx, req)
if err != nil {
	var apiErr *camelmailer.APIError
	if errors.As(err, &apiErr) {
		switch apiErr.Code {
		case "ValidationError", "ParameterMissing":
			// fix the request
		case "Unauthorized":
			// check the API key
		}
	}
}

All methods take a context.Context and respect cancellation and deadlines.

Docs

Full API documentation: camelmailer.com/docs

License

MIT

Documentation

Overview

Package camelmailer is the official Go SDK for the CamelMailer transactional email platform (https://camelmailer.com).

It covers the Messaging API (/api/v2/server), authenticated with a server API key:

client := camelmailer.NewClient("cm_xxxx")
sent, err := client.Emails.Send(ctx, &camelmailer.SendEmailRequest{
	From:     camelmailer.Address{Email: "billing@acme.com"},
	To:       []camelmailer.Address{{Email: "ada@example.com"}},
	Subject:  "Your receipt",
	TextBody: "Thanks for your purchase.",
})

Self-hosted instances configure their own base URL with WithBaseURL. API failures are returned as *APIError and can be inspected with errors.As.

Index

Constants

View Source
const DefaultBaseURL = "https://app.camelmailer.com"

DefaultBaseURL is the CamelMailer cloud instance. Self-hosted users override it with WithBaseURL.

View Source
const Version = "0.1.0"

Version is the SDK version, sent in the User-Agent header.

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) *bool

Bool returns a pointer to b, for optional request fields.

func String

func String(s string) *string

String returns a pointer to s, for optional request fields.

Types

type APIError

type APIError struct {
	// Code is the stable machine-readable error code.
	Code string `json:"code"`
	// Message is the human-readable description.
	Message string `json:"message"`
	// StatusCode is the HTTP status of the response.
	StatusCode int `json:"-"`
}

APIError is a typed CamelMailer API failure. Every error envelope (and every non-2xx response) surfaces as *APIError, so callers can branch on the stable error code:

var apiErr *camelmailer.APIError
if errors.As(err, &apiErr) && apiErr.Code == "ValidationError" { … }

Stable codes include Unauthorized, Forbidden, NotFound, ValidationError, ParameterMissing and InternalServerError.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

type ActivityEvent

type ActivityEvent struct {
	// IPAddress is the client IP.
	IPAddress string `json:"ip_address"`
	// UserAgent is the client User-Agent.
	UserAgent string `json:"user_agent"`
	// URL is the clicked link (empty for opens).
	URL string `json:"url"`
	// CreatedAt is the event timestamp.
	CreatedAt time.Time `json:"created_at"`
}

ActivityEvent is one open or click event of a message.

type Address

type Address struct {
	// Email is the address itself (required).
	Email string `json:"email"`
	// Name is the optional display name.
	Name string `json:"name,omitempty"`
}

Address is an email address with an optional display name. It marshals to a bare string ("ada@example.com") when Name is empty and to {"email": …, "name": …} otherwise, and unmarshals from either form.

func (Address) MarshalJSON

func (a Address) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Address) UnmarshalJSON

func (a *Address) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, accepting both a bare email string and an {email, name} object.

type Attachment

type Attachment struct {
	// Name is the file name, e.g. "invoice.pdf".
	Name string `json:"name"`
	// ContentType is the MIME type, e.g. "application/pdf".
	ContentType string `json:"content_type"`
	// Data is the raw file content.
	Data []byte `json:"data_base64"`
}

Attachment is a file attached to an outgoing message. Data is base64-encoded on the wire automatically.

type BatchEntryResult

type BatchEntryResult struct {
	// Status is "success" or "error".
	Status string `json:"status"`
	// Data is the send result when Status is "success".
	Data *SendResult `json:"data,omitempty"`
	// Error describes the failure when Status is "error".
	Error *APIError `json:"error,omitempty"`
}

BatchEntryResult is the outcome of one entry in a batch send. Either Data (Status "success") or Error (Status "error") is set.

type BatchSendResult

type BatchSendResult struct {
	// Messages holds one result per submitted message.
	Messages []BatchEntryResult `json:"messages"`
}

BatchSendResult is the response of a batch send; entries are in request order.

type BouncesService

type BouncesService struct {
	// contains filtered or unexported fields
}

BouncesService reads bounced messages via /api/v2/server/bounces.

func (*BouncesService) Get

func (s *BouncesService) Get(ctx context.Context, id int64) (*Message, error)

Get returns one bounced message by id.

API: GET /api/v2/server/bounces/{id}

func (*BouncesService) List

List returns the server's bounced messages, filtered and paginated. opts may be nil.

API: GET /api/v2/server/bounces

type Client

type Client struct {

	// Emails sends and reads messages.
	Emails *EmailsService
	// Templates manages stored message templates.
	Templates *TemplatesService
	// Streams manages message streams.
	Streams *StreamsService
	// Stats reads message and delivery-queue counters.
	Stats *StatsService
	// Bounces reads bounced messages.
	Bounces *BouncesService
	// DMARC reads stored DMARC aggregate reports and summaries.
	DMARC *DMARCService
	// contains filtered or unexported fields
}

Client talks to one CamelMailer server through the Messaging API. Create it with NewClient; the zero value is not usable.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient returns a Client authenticated with the given server API key (the X-Server-API-Key credential of one mail server).

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) (*PingResult, error)

Ping validates the API key against GET /api/v2/server/ping and reports which server it is scoped to.

type CreateStreamRequest

type CreateStreamRequest struct {
	// Name is the display name (required).
	Name string `json:"name"`
	// Permalink overrides the generated permalink.
	Permalink string `json:"permalink,omitempty"`
	// StreamType is "transactional" (default), "broadcast" or
	// "inbound".
	StreamType string `json:"stream_type,omitempty"`
}

CreateStreamRequest is the payload for StreamsService.Create.

type CreateTemplateRequest

type CreateTemplateRequest struct {
	// Name is the display name (required).
	Name string `json:"name"`
	// Permalink overrides the generated permalink.
	Permalink string `json:"permalink,omitempty"`
	// Subject is the subject template.
	Subject string `json:"subject,omitempty"`
	// HTMLBody is the HTML body template.
	HTMLBody string `json:"html_body,omitempty"`
	// TextBody is the plain-text body template.
	TextBody string `json:"text_body,omitempty"`
}

CreateTemplateRequest is the payload for TemplatesService.Create.

type DMARCRecord

type DMARCRecord struct {
	// ID is the numeric record id.
	ID int64 `json:"id"`
	// SourceIP is the sending IP address.
	SourceIP string `json:"source_ip"`
	// Count is the number of messages this row covers.
	Count int64 `json:"count"`
	// Disposition is "none", "quarantine" or "reject".
	Disposition string `json:"disposition"`
	// DKIMResult is the raw DKIM result, e.g. "pass".
	DKIMResult string `json:"dkim_result"`
	// SPFResult is the raw SPF result, e.g. "softfail".
	SPFResult string `json:"spf_result"`
	// DKIMAligned reports DKIM identifier alignment.
	DKIMAligned bool `json:"dkim_aligned"`
	// SPFAligned reports SPF identifier alignment.
	SPFAligned bool `json:"spf_aligned"`
	// HeaderFrom is the From-header domain.
	HeaderFrom string `json:"header_from"`
	// EnvelopeFrom is the envelope-sender domain.
	EnvelopeFrom string `json:"envelope_from"`
}

DMARCRecord is one row of a DMARC aggregate report.

type DMARCReport

type DMARCReport struct {
	// ID is the numeric report id.
	ID int64 `json:"id"`
	// Domain is the reported domain.
	Domain string `json:"domain"`
	// OrgName is the reporting organization, e.g. "google.com".
	OrgName string `json:"org_name"`
	// OrgEmail is the reporting organization's contact address.
	OrgEmail string `json:"org_email"`
	// ReportID is the reporter's report id.
	ReportID string `json:"report_id"`
	// DateRangeBegin is the start of the covered range.
	DateRangeBegin time.Time `json:"date_range_begin"`
	// DateRangeEnd is the end of the covered range.
	DateRangeEnd time.Time `json:"date_range_end"`
	// ReceivedAt is when the report was ingested.
	ReceivedAt time.Time `json:"received_at"`
	// RecordCount is the number of rows in the report.
	RecordCount int64 `json:"record_count"`
}

DMARCReport is one stored DMARC aggregate report.

type DMARCReportDetail

type DMARCReportDetail struct {
	// Report is the aggregate report.
	Report DMARCReport `json:"report"`
	// Records lists the report's rows.
	Records []DMARCRecord `json:"records"`
}

DMARCReportDetail is one report with its rows, as returned by DMARCService.Report.

type DMARCService

type DMARCService struct {
	// contains filtered or unexported fields
}

DMARCService reads stored DMARC aggregate reports and compliance summaries via /api/v2/server/dmarc.

func (*DMARCService) Report

func (s *DMARCService) Report(ctx context.Context, id int64) (*DMARCReportDetail, error)

Report returns one stored DMARC report with its records.

API: GET /api/v2/server/dmarc/reports/{id}

func (*DMARCService) Reports

Reports returns the stored DMARC aggregate reports, filtered and paginated. opts may be nil.

API: GET /api/v2/server/dmarc/reports

func (*DMARCService) Summary

Summary returns the DMARC compliance summary over the stored aggregate-report rows. opts may be nil.

API: GET /api/v2/server/dmarc/summary

type DMARCSource

type DMARCSource struct {
	// SourceIP is the sending IP address.
	SourceIP string `json:"source_ip"`
	// Count is the number of covered messages from this source.
	Count int64 `json:"count"`
	// SPFAlignedPct is the percentage of SPF-aligned messages.
	SPFAlignedPct float64 `json:"spf_aligned_pct"`
	// DKIMAlignedPct is the percentage of DKIM-aligned messages.
	DKIMAlignedPct float64 `json:"dkim_aligned_pct"`
	// DispositionCounts counts messages per disposition.
	DispositionCounts map[string]int64 `json:"disposition_counts"`
}

DMARCSource is one sending source in a DMARC summary (top 20 by volume).

type DMARCSummary

type DMARCSummary struct {
	// Total is the number of messages covered by the reports.
	Total int64 `json:"total"`
	// Pass counts messages with DKIM and SPF aligned.
	Pass int64 `json:"pass"`
	// Fail counts messages failing alignment.
	Fail int64 `json:"fail"`
	// PassRate is Pass / Total (0.0–1.0).
	PassRate float64 `json:"pass_rate"`
	// BySource lists the top 20 sending sources by volume.
	BySource []DMARCSource `json:"by_source"`
	// ByDisposition counts messages per disposition.
	ByDisposition map[string]int64 `json:"by_disposition"`
}

DMARCSummary aggregates the stored DMARC aggregate-report rows.

type DMARCSummaryOptions

type DMARCSummaryOptions struct {
	// Domain restricts to one reported domain.
	Domain string
	// From is the inclusive window start.
	From time.Time
	// To is the inclusive window end.
	To time.Time
}

DMARCSummaryOptions filters DMARCService.Summary. Zero values are omitted; From/To match reports whose date range overlaps the window.

type Delivery

type Delivery struct {
	// ID is the numeric delivery id.
	ID int64 `json:"id"`
	// Status is the attempt outcome, e.g. "Sent" or "SoftFail".
	Status string `json:"status"`
	// Details is the human-readable outcome description.
	Details string `json:"details"`
	// Output is the remote server output.
	Output string `json:"output"`
	// SentWithSSL reports whether TLS was used.
	SentWithSSL bool `json:"sent_with_ssl"`
	// CreatedAt is the attempt timestamp.
	CreatedAt time.Time `json:"created_at"`
}

Delivery is one delivery attempt of a message.

type DeliveryStats

type DeliveryStats struct {
	// Queued is the total number of queued messages.
	Queued int64 `json:"queued"`
	// Domains breaks the queue down by recipient domain.
	Domains []DomainQueue `json:"domains"`
}

DeliveryStats describes the outbound delivery queue.

type DomainQueue

type DomainQueue struct {
	// Domain is the recipient domain.
	Domain string `json:"domain"`
	// Queued is the number of queued messages for the domain.
	Queued int64 `json:"queued"`
}

DomainQueue is the queued-message count for one recipient domain.

type Email

type Email struct {
	// Message is the stored message.
	Message Message `json:"message"`
	// Deliveries lists its delivery attempts.
	Deliveries []Delivery `json:"deliveries"`
}

Email is one message with its delivery attempts, as returned by EmailsService.Get.

type EmailsService

type EmailsService struct {
	// contains filtered or unexported fields
}

EmailsService sends and reads messages via /api/v2/server/messages.

func (*EmailsService) Clicks

func (s *EmailsService) Clicks(ctx context.Context, id int64) ([]ActivityEvent, error)

Clicks returns the click events of a message.

API: GET /api/v2/server/messages/{id}/clicks

func (*EmailsService) Deliveries

func (s *EmailsService) Deliveries(ctx context.Context, id int64) ([]Delivery, error)

Deliveries returns the delivery attempts of a message.

API: GET /api/v2/server/messages/{id}/deliveries

func (*EmailsService) Get

func (s *EmailsService) Get(ctx context.Context, id int64) (*Email, error)

Get returns one message with its delivery attempts.

API: GET /api/v2/server/messages/{id}

func (*EmailsService) List

List returns the server's messages, filtered and paginated. opts may be nil.

API: GET /api/v2/server/messages

func (*EmailsService) Opens

func (s *EmailsService) Opens(ctx context.Context, id int64) ([]ActivityEvent, error)

Opens returns the open events of a message.

API: GET /api/v2/server/messages/{id}/opens

func (*EmailsService) Raw

func (s *EmailsService) Raw(ctx context.Context, id int64) ([]byte, error)

Raw returns the raw RFC 5322 source of a message, decoded from the API's base64 representation. Servers in privacy mode return a NotAvailable error instead.

API: GET /api/v2/server/messages/{id}/raw

func (*EmailsService) Send

Send queues one message per recipient.

API: POST /api/v2/server/messages

func (*EmailsService) SendBatch

func (s *EmailsService) SendBatch(ctx context.Context, reqs []*SendEmailRequest) (*BatchSendResult, error)

SendBatch queues many messages in one call and returns one result per entry; individual entries can fail without failing the batch.

API: POST /api/v2/server/messages/batch

func (*EmailsService) SendWithTemplate

func (s *EmailsService) SendWithTemplate(ctx context.Context, req *SendWithTemplateRequest) (*SendResult, error)

SendWithTemplate renders a stored template against req.TemplateModel and sends the result.

API: POST /api/v2/server/messages/with_template

func (*EmailsService) SendWithTemplateBatch

func (s *EmailsService) SendWithTemplateBatch(ctx context.Context, reqs []*SendWithTemplateRequest) (*BatchSendResult, error)

SendWithTemplateBatch sends a stored template to many recipients in one call and returns one result per entry.

API: POST /api/v2/server/messages/with_template/batch

type ListBouncesOptions

type ListBouncesOptions struct {
	ListOptions
	// Scope restricts to "incoming" or "outgoing" messages.
	Scope string
	// Status restricts to one delivery status.
	Status string
	// Tag restricts to one tag.
	Tag string
	// Query is a substring match on subject and addresses.
	Query string
}

ListBouncesOptions filters BouncesService.List.

type ListBouncesResult

type ListBouncesResult struct {
	// Bounces is the page of bounced messages.
	Bounces []Message `json:"bounces"`
	// Pagination describes the page window.
	Pagination Pagination `json:"pagination"`
}

ListBouncesResult is one page of bounced messages.

type ListDMARCReportsOptions

type ListDMARCReportsOptions struct {
	ListOptions
	// Domain restricts to one reported domain.
	Domain string
	// From is the inclusive window start.
	From time.Time
	// To is the inclusive window end.
	To time.Time
}

ListDMARCReportsOptions filters DMARCService.Reports.

type ListDMARCReportsResult

type ListDMARCReportsResult struct {
	// Reports is the page of reports, newest report range first.
	Reports []DMARCReport `json:"reports"`
	// Pagination describes the page window.
	Pagination Pagination `json:"pagination"`
}

ListDMARCReportsResult is one page of DMARC aggregate reports.

type ListEmailsOptions

type ListEmailsOptions struct {
	ListOptions
	// Scope restricts to "incoming" or "outgoing" messages.
	Scope string
	// Status restricts to one delivery status.
	Status string
	// Tag restricts to one tag.
	Tag string
	// Query is a substring match on subject and addresses.
	Query string
	// Stream restricts to one message stream (by permalink).
	Stream string
}

ListEmailsOptions filters EmailsService.List.

type ListEmailsResult

type ListEmailsResult struct {
	// Messages is the page of messages.
	Messages []Message `json:"messages"`
	// Pagination describes the page window.
	Pagination Pagination `json:"pagination"`
}

ListEmailsResult is one page of messages.

type ListOptions

type ListOptions struct {
	// Page is the 1-based page number (default 1).
	Page int
	// PerPage is the page size, capped at 100 (default 25).
	PerPage int
}

ListOptions selects a page of a paginated list endpoint.

type Message

type Message struct {
	// ID is the numeric message id.
	ID int64 `json:"id"`
	// Token is the public message token.
	Token string `json:"token"`
	// Scope is "incoming" or "outgoing".
	Scope string `json:"scope"`
	// RcptTo is the recipient address.
	RcptTo string `json:"rcpt_to"`
	// MailFrom is the envelope sender.
	MailFrom string `json:"mail_from"`
	// Subject is the message subject.
	Subject string `json:"subject"`
	// MessageID is the Message-ID header value.
	MessageID string `json:"message_id"`
	// Tag is the message tag.
	Tag string `json:"tag"`
	// Status is the delivery status, e.g. "Sent".
	Status string `json:"status"`
	// Bounce reports whether this message is a bounce.
	Bounce bool `json:"bounce"`
	// SpamStatus is the spam-check verdict.
	SpamStatus string `json:"spam_status"`
	// SpamScore is the spam-check score.
	SpamScore float64 `json:"spam_score"`
	// Held reports whether the message is held.
	Held bool `json:"held"`
	// Threat reports whether a threat was detected.
	Threat bool `json:"threat"`
	// Size is the message size in bytes.
	Size int64 `json:"size"`
	// Metadata is the arbitrary JSON stored with the message.
	Metadata map[string]any `json:"metadata"`
	// StreamID is the id of the message stream.
	StreamID int64 `json:"stream_id"`
	// Bypassed reports whether hold rules were bypassed.
	Bypassed bool `json:"bypassed"`
	// CreatedAt is the creation timestamp.
	CreatedAt time.Time `json:"created_at"`
}

Message is a stored (incoming or outgoing) message.

type Option

type Option func(*Client)

Option configures a Client created by NewClient.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL points the client at a self-hosted CamelMailer instance, e.g. "https://mail.example.com". A trailing slash is ignored.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient replaces the underlying *http.Client, e.g. to set timeouts, proxies, or custom transports.

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent overrides the User-Agent header sent with every request.

type Pagination

type Pagination struct {
	// Page is the 1-based page number.
	Page int `json:"page"`
	// PerPage is the page size (1–100, default 25).
	PerPage int `json:"per_page"`
	// Total is the total number of items.
	Total int64 `json:"total"`
	// TotalPages is the total number of pages.
	TotalPages int64 `json:"total_pages"`
}

Pagination describes the page window of a list response.

type PingResult

type PingResult struct {
	// Pong is true when the API key resolved to a server.
	Pong bool `json:"pong"`
	// ServerID is the numeric id of the authenticated server.
	ServerID int64 `json:"server_id"`
	// Server is the permalink of the authenticated server.
	Server string `json:"server"`
}

PingResult is the response of Client.Ping.

type RenderedTemplate

type RenderedTemplate struct {
	// Subject is the rendered subject.
	Subject *string `json:"subject"`
	// HTMLBody is the rendered HTML body.
	HTMLBody *string `json:"html_body"`
	// TextBody is the rendered plain-text body.
	TextBody *string `json:"text_body"`
}

RenderedTemplate is a template rendered against a model. Fields are nil when the template has no corresponding part.

type SendEmailRequest

type SendEmailRequest struct {
	// From is the sender address.
	From Address `json:"from"`
	// To lists the primary recipients.
	To []Address `json:"to,omitempty"`
	// Cc lists the carbon-copy recipients.
	Cc []Address `json:"cc,omitempty"`
	// Bcc lists the blind-carbon-copy recipients.
	Bcc []Address `json:"bcc,omitempty"`
	// ReplyTo lists the Reply-To addresses.
	ReplyTo []Address `json:"reply_to,omitempty"`
	// Subject is the message subject.
	Subject string `json:"subject,omitempty"`
	// HTMLBody is the HTML part.
	HTMLBody string `json:"html_body,omitempty"`
	// TextBody is the plain-text part.
	TextBody string `json:"text_body,omitempty"`
	// Headers sets extra message headers.
	Headers map[string]string `json:"headers,omitempty"`
	// Attachments lists file attachments.
	Attachments []Attachment `json:"attachments,omitempty"`
	// Tag is a free-form tag for filtering and stats.
	Tag string `json:"tag,omitempty"`
	// Metadata is arbitrary JSON stored with the message.
	Metadata map[string]any `json:"metadata,omitempty"`
	// Stream is a message-stream permalink; defaults to the server's
	// default stream.
	Stream string `json:"stream,omitempty"`
}

SendEmailRequest is the payload for EmailsService.Send. From and at least one recipient (To, Cc or Bcc) are required; the From domain must be a verified sending domain (or confirmed sender address) of the server.

type SendRecipient

type SendRecipient struct {
	// RcptTo is the recipient address.
	RcptTo string `json:"rcpt_to"`
	// MessageID is the id of the stored message for this recipient.
	MessageID int64 `json:"message_id"`
	// Token is the public token of the stored message.
	Token string `json:"token"`
	// Status is the queue status, e.g. "queued".
	Status string `json:"status"`
}

SendRecipient is the per-recipient outcome of a send.

type SendResult

type SendResult struct {
	// MessageID is the id of the first stored message.
	MessageID int64 `json:"message_id"`
	// Recipients holds one entry per recipient.
	Recipients []SendRecipient `json:"recipients"`
}

SendResult is the response of a single send.

type SendWithTemplateRequest

type SendWithTemplateRequest struct {
	SendEmailRequest
	// Template is the permalink of the stored template (required).
	Template string `json:"template"`
	// TemplateModel provides the values for the template's
	// {{ variables }}.
	TemplateModel map[string]any `json:"template_model,omitempty"`
}

SendWithTemplateRequest is the payload for EmailsService.SendWithTemplate. The embedded SendEmailRequest fields are flattened on the wire; fields set directly (e.g. Subject) override the rendered template fields.

type Stats

type Stats struct {
	// Total is the total number of messages.
	Total int64 `json:"total"`
	// Incoming counts incoming messages.
	Incoming int64 `json:"incoming"`
	// Outgoing counts outgoing messages.
	Outgoing int64 `json:"outgoing"`
	// Sent counts successfully sent messages.
	Sent int64 `json:"sent"`
	// Pending counts messages waiting in the queue.
	Pending int64 `json:"pending"`
	// Held counts held messages.
	Held int64 `json:"held"`
	// Bounced counts bounced messages.
	Bounced int64 `json:"bounced"`
	// SoftFail counts soft delivery failures.
	SoftFail int64 `json:"soft_fail"`
	// HardFail counts hard delivery failures.
	HardFail int64 `json:"hard_fail"`
	// Opens counts open events.
	Opens int64 `json:"opens"`
	// Clicks counts click events.
	Clicks int64 `json:"clicks"`
	// UniqueOpens counts messages opened at least once.
	UniqueOpens int64 `json:"unique_opens"`
	// UniqueClicks counts messages clicked at least once.
	UniqueClicks int64 `json:"unique_clicks"`
}

Stats are aggregate message and engagement counters of the server.

type StatsOptions

type StatsOptions struct {
	// From is the inclusive window start.
	From time.Time
	// To is the inclusive window end.
	To time.Time
}

StatsOptions restricts StatsService.Get to a created-at window. Zero times are omitted.

type StatsService

type StatsService struct {
	// contains filtered or unexported fields
}

StatsService reads message and delivery-queue counters via /api/v2/server/stats.

func (*StatsService) Deliveries

func (s *StatsService) Deliveries(ctx context.Context) (*DeliveryStats, error)

Deliveries returns the current outbound queue depth, broken down by recipient domain.

API: GET /api/v2/server/stats/deliveries

func (*StatsService) Get

func (s *StatsService) Get(ctx context.Context, opts *StatsOptions) (*Stats, error)

Get returns the server's message counters, optionally restricted to a time window. opts may be nil.

API: GET /api/v2/server/stats

type Stream

type Stream struct {
	// ID is the numeric stream id.
	ID int64 `json:"id"`
	// UUID is the stable unique identifier.
	UUID string `json:"uuid"`
	// Name is the display name.
	Name string `json:"name"`
	// Permalink identifies the stream in API calls and send requests.
	Permalink string `json:"permalink"`
	// StreamType is "transactional", "broadcast" or "inbound".
	StreamType string `json:"stream_type"`
	// Archived reports whether the stream is archived.
	Archived bool `json:"archived"`
}

Stream is a message stream of the server.

type StreamsService

type StreamsService struct {
	// contains filtered or unexported fields
}

StreamsService manages message streams via /api/v2/server/streams.

func (*StreamsService) Archive

func (s *StreamsService) Archive(ctx context.Context, permalink string) (*Stream, error)

Archive archives a stream; archived streams reject new messages.

API: POST /api/v2/server/streams/{permalink}/archive

func (*StreamsService) Create

func (s *StreamsService) Create(ctx context.Context, req *CreateStreamRequest) (*Stream, error)

Create adds a message stream.

API: POST /api/v2/server/streams

func (*StreamsService) Get

func (s *StreamsService) Get(ctx context.Context, permalink string) (*Stream, error)

Get returns one stream by permalink.

API: GET /api/v2/server/streams/{permalink}

func (*StreamsService) List

func (s *StreamsService) List(ctx context.Context) ([]Stream, error)

List returns all message streams of the server.

API: GET /api/v2/server/streams

func (*StreamsService) Update

func (s *StreamsService) Update(ctx context.Context, permalink string, req *UpdateStreamRequest) (*Stream, error)

Update changes the given fields of a stream.

API: PATCH /api/v2/server/streams/{permalink}

type Template

type Template struct {
	// ID is the numeric template id.
	ID int64 `json:"id"`
	// UUID is the stable unique identifier.
	UUID string `json:"uuid"`
	// Name is the display name.
	Name string `json:"name"`
	// Permalink identifies the template in API calls.
	Permalink string `json:"permalink"`
	// Subject is the subject template.
	Subject string `json:"subject"`
	// HTMLBody is the HTML body template.
	HTMLBody string `json:"html_body"`
	// TextBody is the plain-text body template.
	TextBody string `json:"text_body"`
	// Archived reports whether the template is archived.
	Archived bool `json:"archived"`
}

Template is a stored message template.

type TemplatesService

type TemplatesService struct {
	// contains filtered or unexported fields
}

TemplatesService manages stored message templates via /api/v2/server/templates. Template subjects and bodies may contain Mustache-style {{ variables }}.

func (*TemplatesService) Archive

func (s *TemplatesService) Archive(ctx context.Context, permalink string) (*Template, error)

Archive archives a template.

API: POST /api/v2/server/templates/{permalink}/archive

func (*TemplatesService) Create

Create stores a new template.

API: POST /api/v2/server/templates

func (*TemplatesService) Get

func (s *TemplatesService) Get(ctx context.Context, permalink string) (*Template, error)

Get returns one template by permalink.

API: GET /api/v2/server/templates/{permalink}

func (*TemplatesService) List

func (s *TemplatesService) List(ctx context.Context) ([]Template, error)

List returns all templates of the server.

API: GET /api/v2/server/templates

func (*TemplatesService) Render

func (s *TemplatesService) Render(ctx context.Context, permalink string, model map[string]any) (*RenderedTemplate, error)

Render previews a template against model without sending anything. model may be nil.

API: POST /api/v2/server/templates/{permalink}/render

func (*TemplatesService) Update

func (s *TemplatesService) Update(ctx context.Context, permalink string, req *UpdateTemplateRequest) (*Template, error)

Update changes the given fields of a template.

API: PATCH /api/v2/server/templates/{permalink}

type UpdateStreamRequest

type UpdateStreamRequest struct {
	// Name replaces the display name.
	Name *string `json:"name,omitempty"`
	// StreamType replaces the stream type.
	StreamType *string `json:"stream_type,omitempty"`
	// Archived archives or unarchives the stream.
	Archived *bool `json:"archived,omitempty"`
}

UpdateStreamRequest is the payload for StreamsService.Update. Nil fields are left unchanged; use String and Bool for the pointer fields.

type UpdateTemplateRequest

type UpdateTemplateRequest struct {
	// Name replaces the display name.
	Name *string `json:"name,omitempty"`
	// Subject replaces the subject template.
	Subject *string `json:"subject,omitempty"`
	// HTMLBody replaces the HTML body template.
	HTMLBody *string `json:"html_body,omitempty"`
	// TextBody replaces the plain-text body template.
	TextBody *string `json:"text_body,omitempty"`
	// Archived archives or unarchives the template.
	Archived *bool `json:"archived,omitempty"`
}

UpdateTemplateRequest is the payload for TemplatesService.Update. Nil fields are left unchanged; use String and Bool for the pointer fields.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL