Documentation
¶
Overview ¶
Package fakeemail is the official Go client for the fake-email.pro Public API: create a disposable mailbox, wait for the email, get the one-time code or the magic link. It is built for end-to-end tests of signup, OTP and password-reset flows.
client, err := fakeemail.NewClient() // reads FAKE_EMAIL_API_KEY
if err != nil {
return err
}
mb, err := client.Mailboxes.Create(ctx, nil)
if err != nil {
return err
}
// ...sign up with mb.Address in your app...
code, err := client.WaitForCode(ctx, mb.Address, nil) // "048213"
Every method takes a context.Context first; a cancelled context ends the call with ctx.Err(). Errors from the server are *APIError or one of the status types that embed it (*NotFoundError, *RateLimitError, ...), so both errors.As(err, ¬Found) and errors.As(err, &apiErr) work.
The client is safe for concurrent use. Use it from server-side code only: the API key must never reach a browser.
Example ¶
package main
import (
"context"
"fmt"
"log"
"time"
fakeemail "github.com/fake-email-pro/fake-email-go"
)
func main() {
ctx := context.Background()
client, err := fakeemail.NewClient() // reads FAKE_EMAIL_API_KEY
if err != nil {
log.Fatal(err)
}
// 1. A fresh address, valid for 24 hours
mb, err := client.Mailboxes.Create(ctx, nil)
if err != nil {
log.Fatal(err)
}
defer client.Mailboxes.Delete(ctx, mb.Address)
// 2. Make your app send an email to mb.Address, then
// 3. wait for the email and take the code
code, err := client.WaitForCode(ctx, mb.Address, &fakeemail.WaitOptions{Timeout: 60 * time.Second})
if err != nil {
log.Fatal(err)
}
fmt.Println(code)
}
Output:
Index ¶
- Constants
- Variables
- type APIConnectionError
- type APIError
- type APITimeoutError
- type Attachment
- type AuthenticationError
- type BadRequestError
- type BodyState
- type Client
- func (c *Client) BaseURL() string
- func (c *Client) WaitForCode(ctx context.Context, address string, opts *WaitOptions) (string, error)
- func (c *Client) WaitForLink(ctx context.Context, address string, opts *WaitOptions) (string, error)
- func (c *Client) WaitForMessage(ctx context.Context, address string, opts *WaitOptions) (*SimpleMessage, error)
- type ConflictError
- type CreateMailboxParams
- type DetailedMessage
- type Domain
- type DomainType
- type DomainsService
- type DownloadedAttachment
- type ErrorCode
- type FakeEmailError
- type InternalServerError
- type Limits
- type LimitsService
- type Link
- type ListAllParams
- type Mailbox
- type MailboxPage
- type MailboxesService
- func (s *MailboxesService) Create(ctx context.Context, params *CreateMailboxParams, opts ...RequestOption) (*Mailbox, error)
- func (s *MailboxesService) Delete(ctx context.Context, address string, opts ...RequestOption) error
- func (s *MailboxesService) Get(ctx context.Context, address string, opts ...RequestOption) (*Mailbox, error)
- func (s *MailboxesService) List(ctx context.Context, params *PageParams, opts ...RequestOption) (*MailboxPage, error)
- func (s *MailboxesService) ListAll(ctx context.Context, params *ListAllParams, opts ...RequestOption) iter.Seq2[Mailbox, error]
- type MessagePage
- type MessagesService
- func (s *MessagesService) Attachment(ctx context.Context, address, id, attachmentID string, opts ...RequestOption) (*DownloadedAttachment, error)
- func (s *MessagesService) Delete(ctx context.Context, address, id string, opts ...RequestOption) error
- func (s *MessagesService) Get(ctx context.Context, address, id string, opts ...RequestOption) (*DetailedMessage, error)
- func (s *MessagesService) List(ctx context.Context, address string, params *PageParams, opts ...RequestOption) (*MessagePage, error)
- func (s *MessagesService) ListAll(ctx context.Context, address string, params *ListAllParams, ...) iter.Seq2[SimpleMessage, error]
- func (s *MessagesService) Raw(ctx context.Context, address, id string, opts ...RequestOption) ([]byte, error)
- func (s *MessagesService) Wait(ctx context.Context, address string, params *WaitParams, opts ...RequestOption) (*SimpleMessage, error)
- type NotFoundError
- type Option
- type Page
- type PageParams
- type PermissionDeniedError
- type Quota
- type QuotaExhaustedError
- type RateLimitError
- type RateLimitInfo
- type RequestOption
- type Sender
- type SimpleMessage
- type Storage
- type WaitOptions
- type WaitParams
- type WaitTimeoutError
Examples ¶
Constants ¶
const ( // DefaultBaseURL is the production API. DefaultBaseURL = "https://api.fake-email.pro" // DefaultTimeout is the limit of one HTTP attempt. A wait request always gets its server timeout + 10 s // instead, whatever the client's timeout is. DefaultTimeout = 30 * time.Second // DefaultMaxRetries is how many times a retryable failure is repeated. DefaultMaxRetries = 2 )
const Version = "0.2.0"
Version is the version of this SDK, sent in the User-Agent header as "fake-email-pro-go/<Version>". The release workflow checks that the tag vX.Y.Z equals it.
Variables ¶
var ErrMissingAPIKey error = &clientError{
msg: "missing API key: pass fakeemail.WithAPIKey or set FAKE_EMAIL_API_KEY (create one at https://fake-email.pro/settings/api-keys)",
}
ErrMissingAPIKey is returned by NewClient when no key is given and FAKE_EMAIL_API_KEY is empty.
Functions ¶
This section is empty.
Types ¶
type APIConnectionError ¶
APIConnectionError means the request got no response (DNS, refused connection, reset). Err is the underlying error from the transport.
func (*APIConnectionError) Error ¶
func (e *APIConnectionError) Error() string
func (*APIConnectionError) Unwrap ¶
func (e *APIConnectionError) Unwrap() error
Unwrap returns the transport's error.
type APIError ¶
type APIError struct {
// Status is the HTTP status.
Status int
// Code is the error field of the body; "" when the body is not the JSON envelope (e.g. a proxy's 502).
Code ErrorCode
// Message is the message field of the body, or "HTTP <status>" when the body is not the envelope.
Message string
// Body is the parsed JSON body (map[string]any, ...), or the raw text when it is not JSON, or nil when
// empty.
Body any
// Header holds the response headers.
Header http.Header
// RateLimit is from X-RateLimit-*; nil when the response did not carry them (the state is unknown, not
// zero).
RateLimit *RateLimitInfo
}
APIError means the server answered with a non-2xx status. A status with its own type (400, 401, 402, 403, 404, 409, 429, 5xx) comes as that type, which embeds *APIError and unwraps to it, so errors.As(err, &apiErr) matches every one of them.
Example ¶
package main
import (
"context"
"errors"
"fmt"
fakeemail "github.com/fake-email-pro/fake-email-go"
)
func main() {
ctx := context.Background()
client, _ := fakeemail.NewClient()
_, err := client.Mailboxes.Create(ctx, nil)
var quota *fakeemail.QuotaExhaustedError
var apiErr *fakeemail.APIError
switch {
case errors.As(err, "a):
fmt.Printf("quota %d/%d, renews %s. More: %s\n", quota.Used, quota.Limit, quota.ResetsAt, quota.UpgradeURL)
case errors.As(err, &apiErr): // any other status
fmt.Println(apiErr.Status, apiErr.Code, apiErr.RateLimit)
case errors.Is(err, context.Canceled):
fmt.Println("cancelled")
case err != nil:
fmt.Println(err) // *APIConnectionError, *APITimeoutError
}
}
Output:
type APITimeoutError ¶
type APITimeoutError struct {
*APIConnectionError
}
APITimeoutError means an HTTP attempt took longer than the client's timeout. It unwraps to its *APIConnectionError, which unwraps to the transport's error.
func (*APITimeoutError) Timeout ¶
func (e *APITimeoutError) Timeout() bool
Timeout reports true, like net.Error.
func (*APITimeoutError) Unwrap ¶
func (e *APITimeoutError) Unwrap() error
Unwrap returns the embedded *APIConnectionError.
type Attachment ¶
type Attachment struct {
ID string `json:"id"`
// ContentType is the MIME type as declared by the sender, without parameters.
ContentType string `json:"contentType"`
// FileName is the file name as declared by the sender; nil if there is none.
FileName *string `json:"fileName"`
// SizeBytes is the size of the decoded content.
SizeBytes int64 `json:"sizeBytes"`
}
Attachment describes an attachment of a DetailedMessage; download it with MessagesService.Attachment.
type AuthenticationError ¶
type AuthenticationError struct{ *APIError }
AuthenticationError is 401 unauthorized: the key is missing, unknown, revoked or expired.
func (*AuthenticationError) Unwrap ¶
func (e *AuthenticationError) Unwrap() error
Unwrap returns the embedded *APIError.
type BadRequestError ¶
type BadRequestError struct{ *APIError }
BadRequestError is 400 bad_request: a parameter or the body is invalid.
func (*BadRequestError) Unwrap ¶
func (e *BadRequestError) Unwrap() error
Unwrap returns the embedded *APIError.
type BodyState ¶
type BodyState string
BodyState tells what the server kept of a message.
const ( // BodyStateStored: parsed; the body and the EML are kept. BodyStateStored BodyState = "STORED" // BodyStateUnparsed: could not be parsed; only the EML is kept (no body, attachments, from or subject). BodyStateUnparsed BodyState = "UNPARSED" // BodyStateOverflow: larger than the account's whole storage; only the headers are kept, no EML, SizeBytes 0. BodyStateOverflow BodyState = "OVERFLOW" )
type Client ¶
type Client struct {
Mailboxes *MailboxesService
Messages *MessagesService
Domains *DomainsService
Limits *LimitsService
// contains filtered or unexported fields
}
Client is a client for the fake-email.pro Public API. Create it with NewClient; it is safe for concurrent use. Server-side only: the key must never reach browser code (the API has no CORS).
func NewClient ¶
NewClient creates a client. It fails with ErrMissingAPIKey when no key is given and FAKE_EMAIL_API_KEY is empty.
func (*Client) BaseURL ¶
BaseURL returns the API origin the client sends requests to, without a trailing slash.
func (*Client) WaitForCode ¶
func (c *Client) WaitForCode(ctx context.Context, address string, opts *WaitOptions) (string, error)
WaitForCode waits for a message with a one-time code and returns the code. It uses the code found on delivery, else the first code of the full message; a message without any code is skipped.
func (*Client) WaitForLink ¶
func (c *Client) WaitForLink(ctx context.Context, address string, opts *WaitOptions) (string, error)
WaitForLink waits for a message with a confirm / sign-in link and returns its URL. It uses the link found on delivery, else the first link of the full message; a message without links is skipped.
func (*Client) WaitForMessage ¶
func (c *Client) WaitForMessage(ctx context.Context, address string, opts *WaitOptions) (*SimpleMessage, error)
WaitForMessage waits until a matching message arrives, repeating the server's long poll (up to 60 s each) until opts.Timeout. At the deadline it returns a *WaitTimeoutError.
Example ¶
package main
import (
"context"
"fmt"
"log"
fakeemail "github.com/fake-email-pro/fake-email-go"
)
func main() {
ctx := context.Background()
client, _ := fakeemail.NewClient()
first, err := client.WaitForMessage(ctx, "signup-test@example.org", &fakeemail.WaitOptions{
From: "acme.example", // case-insensitive substring of the sender address
Subject: "verify", // case-insensitive substring of the subject
Match: func(m *fakeemail.SimpleMessage) bool { return m.AttachmentsCount == 0 },
})
if err != nil {
log.Fatal(err)
}
// ...click "Resend code" in your app, then wait for a newer message:
second, err := client.WaitForMessage(ctx, "signup-test@example.org", &fakeemail.WaitOptions{After: first.ID})
if err != nil {
log.Fatal(err)
}
fmt.Println(second.ID)
}
Output:
type ConflictError ¶
type ConflictError struct{ *APIError }
ConflictError is 409 address_taken: the address was issued before, to anyone.
func (*ConflictError) Unwrap ¶
func (e *ConflictError) Unwrap() error
Unwrap returns the embedded *APIError.
type CreateMailboxParams ¶
type CreateMailboxParams struct {
// LocalPart is the local part to use (the server lowercases it); it requires Domain and a plan that allows
// custom local parts.
LocalPart string
// Domain is a domain from Domains.List; random if unset. A domain that is unknown or not available to
// you is a *NotFoundError.
Domain string
}
CreateMailboxParams are the fields of a new mailbox. A zero value means unset; nil params are allowed.
type DetailedMessage ¶
type DetailedMessage struct {
ID string `json:"id"`
CreatedAt time.Time `json:"createdAt"`
// From is nil for BodyStateUnparsed and for a message without From.
From *Sender `json:"from"`
// Subject is nil if there is none or the message was not parsed.
Subject *string `json:"subject"`
BodyState BodyState `json:"bodyState"`
// HTML is the HTML part; nil if there is none, and for BodyStateUnparsed / BodyStateOverflow.
HTML *string `json:"html"`
// Text is the plain-text part (never derived from the HTML); nil if there is none.
Text *string `json:"text"`
// Attachments are in the order of the message's parts.
Attachments []Attachment `json:"attachments"`
// Codes are one-time codes, computed on read; Codes[0] is the best guess.
Codes []string `json:"codes"`
// Links are ranked by how likely they are to "confirm / sign in"; Links[0] is the best guess.
Links []Link `json:"links"`
}
DetailedMessage is the full message: bodies, attachments, every code and link.
type Domain ¶
type Domain struct {
// Name is the domain name in lowercase.
Name string `json:"name"`
Type DomainType `json:"type"`
}
Domain is a domain you can create a mailbox on.
type DomainType ¶
type DomainType string
DomainType is the kind of a domain. PREMIUM is visible only to plans that allow premium domains.
const ( DomainTypePublic DomainType = "PUBLIC" DomainTypePremium DomainType = "PREMIUM" )
type DomainsService ¶
type DomainsService struct {
// contains filtered or unexported fields
}
DomainsService lists domains. Use it as client.Domains.
func (*DomainsService) List ¶
func (s *DomainsService) List(ctx context.Context, opts ...RequestOption) ([]Domain, error)
List returns the domains you can create a mailbox on, sorted by name.
type DownloadedAttachment ¶
type DownloadedAttachment struct {
// Data is the decoded bytes.
Data []byte
// ContentType is from the Content-Type header (application/octet-stream if absent).
ContentType string
// FileName is from Content-Disposition (RFC 5987 filename* preferred). It is never nil from the API: the
// attachment id when the email gave no name (nil only if a proxy dropped the header). The sender chose it:
// keep only filepath.Base of it before saving to disk.
FileName *string
}
DownloadedAttachment is the content of an attachment.
type ErrorCode ¶
type ErrorCode string
ErrorCode is the error field of the API's error envelope; tell errors apart by it.
const ( ErrorCodeBadRequest ErrorCode = "bad_request" ErrorCodeQuotaExhausted ErrorCode = "quota_exhausted" ErrorCodeForbidden ErrorCode = "forbidden" ErrorCodeOAuthRequired ErrorCode = "oauth_required" ErrorCodePlanForbidden ErrorCode = "plan_forbidden" ErrorCodePlanLimitExceeded ErrorCode = "plan_limit_exceeded" ErrorCodeNotFound ErrorCode = "not_found" ErrorCodeMethodNotAllowed ErrorCode = "method_not_allowed" ErrorCodeAddressTaken ErrorCode = "address_taken" ErrorCodeConfirmationRequired ErrorCode = "confirmation_required" ErrorCodeInvalidState ErrorCode = "invalid_state" ErrorCodeDomainExists ErrorCode = "domain_exists" ErrorCodePayloadTooLarge ErrorCode = "payload_too_large" ErrorCodeUnsupportedMediaType ErrorCode = "unsupported_media_type" ErrorCodeRateLimitExceeded ErrorCode = "rate_limit_exceeded" ErrorCodeTooManyWaits ErrorCode = "too_many_waits" ErrorCodeInternalServerError ErrorCode = "internal_server_error" )
type FakeEmailError ¶
type FakeEmailError interface {
error
// contains filtered or unexported methods
}
FakeEmailError is implemented by every error this SDK returns, except ctx.Err() when the context ends:
var fe fakeemail.FakeEmailError
if errors.As(err, &fe) { ... }
The name matches the base error of the other fake-email.pro SDKs.
type InternalServerError ¶
type InternalServerError struct{ *APIError }
InternalServerError is any 5xx, including a proxy's 502 during a server restart, Cloudflare's 520-524 and 503 service unavailable.
func (*InternalServerError) Unwrap ¶
func (e *InternalServerError) Unwrap() error
Unwrap returns the embedded *APIError.
type Limits ¶
type Limits struct {
Quota Quota `json:"quota"`
// RequestsPerMinute is the rate limit per user (X-RateLimit-Limit).
RequestsPerMinute int `json:"requestsPerMinute"`
// ConcurrentWaits is how many wait requests may be held open at once per user.
ConcurrentWaits int `json:"concurrentWaits"`
Storage Storage `json:"storage"`
// MailboxTTLSeconds is how long a mailbox accepts mail after creation.
MailboxTTLSeconds int `json:"mailboxTtlSeconds"`
}
Limits are the numbers that apply to you right now, under your current plan.
type LimitsService ¶
type LimitsService struct {
// contains filtered or unexported fields
}
LimitsService reads your plan's numbers. Use it as client.Limits.
func (*LimitsService) Get ¶
func (s *LimitsService) Get(ctx context.Context, opts ...RequestOption) (*Limits, error)
Get returns your quota, rate limit, concurrent waits, storage and mailbox lifetime. It does not spend quota.
type Link ¶
type Link struct {
// URL is http:// or https:// only.
URL string `json:"url"`
// Text is the visible link text (or the image's alt); nil for bare URLs.
Text *string `json:"text"`
}
Link is a link found in a message.
type ListAllParams ¶
type ListAllParams struct {
// Size is the page size used while iterating, 1..50 (default 50).
Size int
}
ListAllParams configure ListAll. nil is allowed.
type Mailbox ¶
type Mailbox struct {
// Address is localPart@domain in lowercase.
Address string `json:"address"`
// ActiveSince is the creation time.
ActiveSince time.Time `json:"activeSince"`
// ExpiresAt is when the mailbox stops accepting mail; from then on it and its messages are 404.
ExpiresAt time.Time `json:"expiresAt"`
// StorageUsedBytes is the sum of SizeBytes of the mailbox's messages.
StorageUsedBytes int64 `json:"storageUsedBytes"`
// MessagesCount is the number of messages in the mailbox.
MessagesCount int `json:"messagesCount"`
}
Mailbox is an active API mailbox. It accepts mail for 24 hours after creation, then is deleted together with its messages.
type MailboxesService ¶
type MailboxesService struct {
// contains filtered or unexported fields
}
MailboxesService creates, lists, reads and deletes mailboxes. Use it as client.Mailboxes.
func (*MailboxesService) Create ¶
func (s *MailboxesService) Create(ctx context.Context, params *CreateMailboxParams, opts ...RequestOption) (*Mailbox, error)
Create creates a mailbox, spending one unit of the monthly quota. With nil params: a random address on a random domain. A 503 whose Retry-After is over 5 s (no domain to issue an address on right now) is returned at once rather than retried.
func (*MailboxesService) Delete ¶
func (s *MailboxesService) Delete(ctx context.Context, address string, opts ...RequestOption) error
Delete deletes the mailbox and its messages. The address is never issued again; the quota is not given back. A retry that finds it gone (the first attempt's answer was lost) is success.
func (*MailboxesService) Get ¶
func (s *MailboxesService) Get(ctx context.Context, address string, opts ...RequestOption) (*Mailbox, error)
Get returns an active mailbox of yours.
func (*MailboxesService) List ¶
func (s *MailboxesService) List(ctx context.Context, params *PageParams, opts ...RequestOption) (*MailboxPage, error)
List returns one page of active mailboxes, newest first.
func (*MailboxesService) ListAll ¶
func (s *MailboxesService) ListAll(ctx context.Context, params *ListAllParams, opts ...RequestOption) iter.Seq2[Mailbox, error]
ListAll yields every active mailbox, fetching pages as needed. On an error it yields the error once and stops.
for mb, err := range client.Mailboxes.ListAll(ctx, nil) {
if err != nil {
return err
}
fmt.Println(mb.Address)
}
Example ¶
package main
import (
"context"
"fmt"
"log"
fakeemail "github.com/fake-email-pro/fake-email-go"
)
func main() {
ctx := context.Background()
client, _ := fakeemail.NewClient()
for mb, err := range client.Mailboxes.ListAll(ctx, nil) {
if err != nil {
log.Fatal(err)
}
fmt.Println(mb.Address, mb.ExpiresAt)
}
}
Output:
type MessagesService ¶
type MessagesService struct {
// contains filtered or unexported fields
}
MessagesService lists, waits for, reads and deletes messages. Use it as client.Messages.
func (*MessagesService) Attachment ¶
func (s *MessagesService) Attachment(ctx context.Context, address, id, attachmentID string, opts ...RequestOption) (*DownloadedAttachment, error)
Attachment returns the decoded bytes of an attachment, with its type and file name. The file name is chosen by the sender: strip any directories (filepath.Base) before using it as a path.
Example ¶
package main
import (
"context"
"log"
"os"
"path/filepath"
fakeemail "github.com/fake-email-pro/fake-email-go"
)
func main() {
ctx := context.Background()
client, _ := fakeemail.NewClient()
const address, messageID, attachmentID = "signup-test@example.org", "3c1b5f0e-...", "9a7e2c44-..."
att, err := client.Messages.Attachment(ctx, address, messageID, attachmentID)
if err != nil {
log.Fatal(err)
}
// The sender chose the name ("../../.bashrc" is possible): keep its last element only. The API always
// sends one (the attachment id when the email gave none); the fallback guards "", "." and "/".
name := attachmentID
if att.FileName != nil {
if base := filepath.Base(*att.FileName); base != "." && base != ".." && base != string(filepath.Separator) {
name = base
}
}
if err := os.WriteFile(filepath.Join(os.TempDir(), name), att.Data, 0o600); err != nil {
log.Fatal(err)
}
}
Output:
func (*MessagesService) Delete ¶
func (s *MessagesService) Delete(ctx context.Context, address, id string, opts ...RequestOption) error
Delete deletes a message. A retry that finds it gone (the first attempt's answer was lost) is success.
func (*MessagesService) Get ¶
func (s *MessagesService) Get(ctx context.Context, address, id string, opts ...RequestOption) (*DetailedMessage, error)
Get returns the full message: bodies, attachments, every code and link.
func (*MessagesService) List ¶
func (s *MessagesService) List(ctx context.Context, address string, params *PageParams, opts ...RequestOption) (*MessagePage, error)
List returns one page of the mailbox's messages, newest first. To watch for new mail use Wait or Client.WaitForMessage, not polling.
func (*MessagesService) ListAll ¶
func (s *MessagesService) ListAll(ctx context.Context, address string, params *ListAllParams, opts ...RequestOption) iter.Seq2[SimpleMessage, error]
ListAll yields every message of the mailbox, newest first, fetching pages as needed. On an error it yields the error once and stops.
func (*MessagesService) Raw ¶
func (s *MessagesService) Raw(ctx context.Context, address, id string, opts ...RequestOption) ([]byte, error)
Raw returns the message's EML, byte for byte.
func (*MessagesService) Wait ¶
func (s *MessagesService) Wait(ctx context.Context, address string, params *WaitParams, opts ...RequestOption) (*SimpleMessage, error)
Wait is one long poll: it returns the earliest matching message (strictly after After), or (nil, nil) when the server's timeout passed without one (204). For a loop with a client-side deadline use Client.WaitForMessage.
The HTTP attempt is given the server timeout + 10 s, whatever WithTimeout or the http.Client's Timeout say: a shorter limit would cut a healthy long poll off. WithRequestTimeout can only make it longer.
type NotFoundError ¶
type NotFoundError struct{ *APIError }
NotFoundError is 404 not_found: the mailbox is not an active API mailbox of yours (expired, deleted), the message or attachment is not there, the domain given to Mailboxes.Create is unknown or not available to you, or the After of a wait names a message that is not in the mailbox (deleted). Message tells them apart.
func (*NotFoundError) Unwrap ¶
func (e *NotFoundError) Unwrap() error
Unwrap returns the embedded *APIError.
type Option ¶
type Option func(*config)
Option configures a Client in NewClient.
func WithAPIKey ¶
WithAPIKey sets the API key (fep_…). The default is the FAKE_EMAIL_API_KEY environment variable.
func WithBaseURL ¶
WithBaseURL sets the API origin, optionally with a path prefix. Default DefaultBaseURL; trailing slashes are trimmed.
func WithHTTPClient ¶
WithHTTPClient sets the *http.Client that sends requests (default: a new client with http.DefaultTransport). Its Timeout, if set, applies on top of the SDK's per-attempt timeout, except for wait requests, which it never cuts short.
func WithMaxRetries ¶
WithMaxRetries sets how many times a retryable failure is repeated (default 2): 429 and 503 always (but not a 503 whose Retry-After is over 5 s), 502, 504, Cloudflare's 520-524, timeouts and network errors for GET and DELETE only. The wait helpers do not use it: they wait out transient failures until their deadline.
func WithTimeout ¶
WithTimeout sets the limit of each HTTP attempt (default 30 s). A wait request always gets its server timeout + 10 s instead, shorter or longer.
func WithUserAgent ¶
WithUserAgent appends a token to the SDK's own User-Agent, e.g. "my-e2e-suite/1.0".
type Page ¶
type Page[T any] struct { Content []T `json:"content"` // Page is the zero-based page number. Page int `json:"page"` Size int `json:"size"` TotalPages int `json:"totalPages"` TotalElements int64 `json:"totalElements"` }
Page is one page of a list, newest first.
type PageParams ¶
type PageParams struct {
// Page is the zero-based page number (default 0).
Page int
// Size is the page size, 1..50 (server default 20).
Size int
}
PageParams select one page of a list. A zero value means unset (the server's default); nil is allowed.
type PermissionDeniedError ¶
type PermissionDeniedError struct{ *APIError }
PermissionDeniedError is 403 plan_forbidden: the plan has no API access, or does not allow a custom local part.
func (*PermissionDeniedError) Unwrap ¶
func (e *PermissionDeniedError) Unwrap() error
Unwrap returns the embedded *APIError.
type Quota ¶
type Quota struct {
// Limit is API mailboxes per month on the plan.
Limit int `json:"limit"`
// Used counts API mailboxes created since the 1st of the month in UTC, deleted ones included.
Used int `json:"used"`
// ResetsAt is the 1st of the next month, 00:00 UTC.
ResetsAt time.Time `json:"resetsAt"`
}
Quota is the monthly quota of API mailboxes (calendar month in UTC).
type QuotaExhaustedError ¶
type QuotaExhaustedError struct {
*APIError
// Limit is API mailboxes per month on the plan.
Limit int
// Used is API mailboxes created this month, deleted ones included.
Used int
// ResetsAt is when the quota renews: the 1st of next month, 00:00 UTC.
ResetsAt time.Time
// UpgradeURL is the pricing page.
UpgradeURL string
}
QuotaExhaustedError is 402 quota_exhausted: the monthly mailbox quota is spent. It is not retried: the quota renews at ResetsAt. A field the body did not carry is left at its zero value.
func (*QuotaExhaustedError) Unwrap ¶
func (e *QuotaExhaustedError) Unwrap() error
Unwrap returns the embedded *APIError.
type RateLimitError ¶
type RateLimitError struct {
*APIError
// RetryAfter is from the Retry-After header, rounded up to whole seconds; 0 if absent.
RetryAfter time.Duration
}
RateLimitError is 429: Code is ErrorCodeRateLimitExceeded (requests per minute) or ErrorCodeTooManyWaits (concurrent waits).
func (*RateLimitError) Unwrap ¶
func (e *RateLimitError) Unwrap() error
Unwrap returns the embedded *APIError.
type RateLimitInfo ¶
type RateLimitInfo struct {
// Limit is requests per minute on the plan.
Limit int
// Remaining is requests left in the current window.
Remaining int
// Reset is the end of the window.
Reset time.Time
}
RateLimitInfo is the rate-limit window state from the X-RateLimit-* headers.
type RequestOption ¶
type RequestOption func(*requestConfig)
RequestOption overrides a client setting for one call. Every method accepts them last.
func WithRequestMaxRetries ¶
func WithRequestMaxRetries(n int) RequestOption
WithRequestMaxRetries overrides the client's maxRetries for this call.
func WithRequestTimeout ¶
func WithRequestTimeout(d time.Duration) RequestOption
WithRequestTimeout overrides the client's per-attempt timeout for this call. For Messages.Wait it can only lengthen the attempt beyond the server timeout + 10 s, never shorten it.
type SimpleMessage ¶
type SimpleMessage struct {
ID string `json:"id"`
// MailboxAddress is the address of the message's mailbox.
MailboxAddress string `json:"mailboxAddress"`
// CreatedAt is the delivery time. Do not use it as After: pass the message's ID instead.
CreatedAt time.Time `json:"createdAt"`
// SizeBytes is the EML size; 0 for BodyStateOverflow.
SizeBytes int64 `json:"sizeBytes"`
// From is nil for BodyStateUnparsed and for a message without From.
From *Sender `json:"from"`
// Subject is nil if there is none or the message was not parsed. Never "".
Subject *string `json:"subject"`
BodyState BodyState `json:"bodyState"`
AttachmentsCount int `json:"attachmentsCount"`
// Code is the best one-time code, computed on delivery (= Codes[0] of the full message); nil if none.
Code *string `json:"code"`
// ConfirmLink is the best "confirm / sign in" link, computed on delivery (= Links[0].URL); nil if none.
ConfirmLink *string `json:"confirmLink"`
}
SimpleMessage is a message in a list and in the wait response.
type WaitOptions ¶
type WaitOptions struct {
// Timeout is the client-side deadline for the whole wait (default 60 s). Past it the helpers return a
// *WaitTimeoutError.
Timeout time.Duration
// After returns only messages strictly after this message id or RFC 3339 time (server clock).
After string
// AfterTime is After as a time. Set After or AfterTime, not both.
AfterTime time.Time
// From is a case-insensitive substring of the sender address (server-side filter).
From string
// Subject is a case-insensitive substring of the subject (server-side filter).
Subject string
// Match is a client-side filter; a message that fails it is skipped and the wait continues after it.
Match func(*SimpleMessage) bool
}
WaitOptions configure WaitForMessage, WaitForCode and WaitForLink. A zero value means unset; nil is allowed.
type WaitParams ¶
type WaitParams struct {
// Timeout is how long the server holds the request, 1..60 s, sent in whole seconds rounded up (server
// default 30 s).
Timeout time.Duration
// After returns only messages strictly after this message id (to continue after a message you got) or
// RFC 3339 time (by the server's clock). Do not pass a message's CreatedAt.
After string
// AfterTime is After as a time, sent in UTC with milliseconds. Set After or AfterTime, not both.
AfterTime time.Time
// From is a case-insensitive substring of the sender address.
From string
// Subject is a case-insensitive substring of the subject.
Subject string
}
WaitParams configure one long poll. A zero value means unset; nil is allowed.
type WaitTimeoutError ¶
type WaitTimeoutError struct {
Address string
Timeout time.Duration
// LastErr is the last transient failure the wait met, nil if none: a hint why nothing arrived. It is not
// unwrapped, so errors.As(err, &apiErr) does not match a WaitTimeoutError.
LastErr error
}
WaitTimeoutError means WaitForMessage, WaitForCode or WaitForLink reached their deadline without a matching message. Transient failures met on the way (429, 502, 503, 504, 520-524, network errors, attempt timeouts) are waited out and end as this error too, never as themselves.
func (*WaitTimeoutError) Error ¶
func (e *WaitTimeoutError) Error() string