mailtrap

package module
v0.2.0 Latest Latest
Warning

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

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

README

Mailtrap Go client

CI Go Reference

The official Go client library for the Mailtrap email delivery platform — transactional and bulk sending, email sandbox (testing), and email marketing.

Prerequisites

To get the most out of this Mailtrap.io Go SDK:

Installation

go get github.com/mailtrap/mailtrap-go

Requires Go 1.23 or newer.

Usage

Create a client with your API token:

client, err := mailtrap.NewClient("your-api-token")
if err != nil {
	log.Fatal(err)
}
Sandbox vs Production (easy switching)

Mailtrap lets you test safely in the Email Sandbox and then switch to Production sending with a single flag. In sandbox mode Send captures the email in a sandbox instead of delivering it to real recipients.

Keep the sandbox ID configured and toggle WithSandbox from configuration — the ID is ignored outside sandbox mode, so the exact same code switches environments without touching any call site:

isSandbox := os.Getenv("MAILTRAP_USE_SANDBOX") == "true"

client, err := mailtrap.NewClient("your-api-token",
	mailtrap.WithSandbox(isSandbox),
	mailtrap.WithSandboxID(3000001), // ignored unless sandbox mode is on
)
if err != nil {
	log.Fatal(err)
}

resp, _, err := client.Send(context.Background(), &mailtrap.SendRequest{
	From:    mailtrap.Address{Email: "sender@example.com", Name: "Example"},
	To:      []mailtrap.Address{{Email: "recipient@example.com"}},
	Subject: "Hello from mailtrap-go",
	Text:    "Captured by the sandbox when MAILTRAP_USE_SANDBOX=true.",
})

Supported functionality & Examples

Email API (sending):

  • Transactional, bulk & batch sending — text/HTML, templates, attachments, categories, custom variables & headers — examples/sending

Email API (management):

Email Sandbox (Testing):

Account & organization management:

Contact management:

Errors

Non-2xx responses decode into typed errors that work with errors.As:

_, _, err := client.Projects.List(ctx)

var ve *mailtrap.ValidationError
if errors.As(err, &ve) {
	fmt.Println(ve.Fields) // field -> messages
}

var rle *mailtrap.RateLimitError
if errors.As(err, &rle) {
	time.Sleep(rle.RetryAfter)
}

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/mailtrap/mailtrap-go. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Code of Conduct.

License

This library is released under the MIT License.

Documentation

Overview

Package mailtrap is the official Go client library for the Mailtrap email delivery platform: transactional and bulk sending, the email sandbox (testing), and email marketing.

Construct a client with an API token and optional functional options:

client, err := mailtrap.NewClient("your-api-token")
if err != nil {
	// handle error
}

Index

Constants

View Source
const (
	SpecifierTypeUser     = "User"
	SpecifierTypeInvite   = "Invite"
	SpecifierTypeAPIToken = "ApiToken"
)

Account access specifier types for AccountAccess.SpecifierType.

View Source
const (
	AccessLevelOwner         = 1000
	AccessLevelAdmin         = 100
	AccessLevelViewerPlus    = 50
	AccessLevelViewer        = 10
	AccessLevelIndeterminate = 1
)

Access levels for AccountAccessResource.AccessLevel, Account.AccessLevels, and APITokenPermission.AccessLevel. A higher level grants more rights.

View Source
const (
	ContactExportCreated  = "created"
	ContactExportStarted  = "started"
	ContactExportFinished = "finished"
)

Contact export statuses for ContactExport.Status.

View Source
const (
	ContactExportFilterListID             = "list_id"
	ContactExportFilterSubscriptionStatus = "subscription_status"
)

Contact export filter names for ContactExportFilter.Name.

View Source
const (
	ContactFieldTypeText    = "text"
	ContactFieldTypeInteger = "integer"
	ContactFieldTypeFloat   = "float"
	ContactFieldTypeBoolean = "boolean"
	ContactFieldTypeDate    = "date"
)

Contact field data types for ContactField.DataType.

View Source
const (
	ContactImportCreated  = "created"
	ContactImportStarted  = "started"
	ContactImportFinished = "finished"
	ContactImportFailed   = "failed"
)

Contact import statuses for ContactImport.Status.

View Source
const (
	ContactStatusSubscribed   = "subscribed"
	ContactStatusUnsubscribed = "unsubscribed"
)

Contact subscription statuses for Contact.Status.

View Source
const (
	EmailLogStatusDelivered    = "delivered"
	EmailLogStatusNotDelivered = "not_delivered"
	EmailLogStatusEnqueued     = "enqueued"
	EmailLogStatusOptedOut     = "opted_out"
)

Email log message statuses for EmailLogMessage.Status.

View Source
const (
	MessageEventTypeDelivery    = "delivery"
	MessageEventTypeOpen        = "open"
	MessageEventTypeClick       = "click"
	MessageEventTypeSoftBounce  = "soft_bounce"
	MessageEventTypeBounce      = "bounce"
	MessageEventTypeSpam        = "spam"
	MessageEventTypeUnsubscribe = "unsubscribe"
	MessageEventTypeSuspension  = "suspension"
	MessageEventTypeReject      = "reject"
)

Message event types for MessageEvent.EventType.

View Source
const (
	ResourceTypeAccount            = "account"
	ResourceTypeBilling            = "billing"
	ResourceTypeOrganization       = "organization"
	ResourceTypeProject            = "project"
	ResourceTypeSandbox            = "sandbox"
	ResourceTypeDomain             = "domain"
	ResourceTypeEmailCampaignScope = "email_campaign_permission_scope"
	ResourceTypeEmailTemplateScope = "email_template_permission_scope"
)

Resource types for the resource_type fields of PermissionUpdate, AccountAccessResource, and APITokenPermission, and for PermissionResource.Type.

View Source
const (
	PermissionLevelAdmin  = "admin"
	PermissionLevelViewer = "viewer"
)

Permission access levels for PermissionUpdate.AccessLevel. The bulk-update endpoint also accepts the numeric equivalents ("100", "10").

View Source
const (
	DispositionAttachment = "attachment"
	DispositionInline     = "inline"
)

Attachment disposition values for Attachment.Disposition.

View Source
const (
	InfoLevelBusiness   = "business"
	InfoLevelIndividual = "individual"
)

Company info levels for CompanyInfo.InfoLevel and CompanyInfoRequest.InfoLevel.

View Source
const (
	SuppressionTypeHardBounce     = "hard bounce"
	SuppressionTypeUnsubscription = "unsubscription"
	SuppressionTypeSpamComplaint  = "spam complaint"
	SuppressionTypeManualImport   = "manual import"
)

Suppression reasons for Suppression.Type.

View Source
const (
	SendingStreamTransactional = "transactional"
	SendingStreamBulk          = "bulk"
	SendingStreamAny           = "any"
)

Sending streams. Create accepts transactional or bulk; "any" is response-only.

View Source
const (
	WebhookTypeEmailSending     = "email_sending"
	WebhookTypeCampaigns        = "campaigns"
	WebhookTypeAuditLog         = "audit_log"
	WebhookTypeInboundReceiving = "inbound_receiving"
)

Webhook types for CreateWebhookRequest.WebhookType.

View Source
const (
	PayloadFormatJSON      = "json"
	PayloadFormatJSONLines = "jsonlines"
)

Webhook payload formats for CreateWebhookRequest.PayloadFormat.

View Source
const (
	WebhookEventDelivery      = "delivery"
	WebhookEventSoftBounce    = "soft_bounce"
	WebhookEventBounce        = "bounce"
	WebhookEventSuspension    = "suspension"
	WebhookEventUnsubscribe   = "unsubscribe"
	WebhookEventOpen          = "open"
	WebhookEventSpamComplaint = "spam_complaint"
	WebhookEventClick         = "click"
	WebhookEventReject        = "reject"
)

Webhook event types for CreateWebhookRequest.EventTypes (email_sending and campaigns webhooks).

View Source
const ContactExportOperatorEqual = "equal"

ContactExportOperatorEqual is the only supported ContactExportFilter.Operator.

Variables

This section is empty.

Functions

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v, for setting optional pointer request fields such as UpdateDomainRequest.OpenTrackingEnabled: mailtrap.Ptr(false).

Types

type APIToken added in v0.2.0

type APIToken struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	// Last4Digits is the last four characters of the token value.
	Last4Digits string `json:"last_4_digits,omitempty"`
	// CreatedBy names the user or token that created this token.
	CreatedBy string `json:"created_by,omitempty"`
	// ExpiresAt is the RFC 3339 expiry, or empty if the token does not expire.
	ExpiresAt string                `json:"expires_at,omitempty"`
	Resources []*APITokenPermission `json:"resources,omitempty"`
	// Token is the full token value, returned only by Create and Reset. Store it
	// securely — it is never returned again.
	Token string `json:"token,omitempty"`
}

APIToken is an API token and the permissions granted to it.

type APITokenPermission added in v0.2.0

type APITokenPermission struct {
	// ResourceType identifies the kind of resource.
	ResourceType string `json:"resource_type"`
	ResourceID   int64  `json:"resource_id"`
	// AccessLevel is the level to grant on the resource.
	AccessLevel int `json:"access_level"`
}

APITokenPermission grants a token access to one resource. It appears in both APIToken.Resources and CreateAPITokenRequest.Resources.

type APITokensService added in v0.2.0

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

APITokensService manages the account's API tokens.

func (*APITokensService) Create added in v0.2.0

Create adds an API token. The returned token's Token field holds the full value and is only available here — store it securely.

func (*APITokensService) Delete added in v0.2.0

func (s *APITokensService) Delete(ctx context.Context, tokenID int64) (*Response, error)

Delete permanently removes an API token by ID.

func (*APITokensService) Get added in v0.2.0

func (s *APITokensService) Get(ctx context.Context, tokenID int64) (*APIToken, *Response, error)

Get returns an API token by ID. The full token value is not included; it is only returned by Create and Reset.

func (*APITokensService) List added in v0.2.0

func (s *APITokensService) List(ctx context.Context) ([]*APIToken, *Response, error)

List returns all API tokens visible to the current token.

func (*APITokensService) Reset added in v0.2.0

func (s *APITokensService) Reset(ctx context.Context, tokenID int64) (*APIToken, *Response, error)

Reset expires the token and issues a replacement with the same permissions. The returned token's Token field holds the new value; store it securely.

type Account added in v0.2.0

type Account struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	// AccessLevels holds the token's access levels for the account.
	AccessLevels []int `json:"access_levels"`
}

Account is a Mailtrap account the token has access to.

type AccountAccess added in v0.2.0

type AccountAccess struct {
	ID int64 `json:"id"`
	// SpecifierType identifies the kind of entity that holds the access.
	SpecifierType string                    `json:"specifier_type"`
	Specifier     *AccountAccessSpecifier   `json:"specifier"`
	Resources     []*AccountAccessResource  `json:"resources"`
	Permissions   *AccountAccessPermissions `json:"permissions"`
}

AccountAccess assigns resource-specific permissions to a specifier (a user, invite, or API token).

type AccountAccessListOptions added in v0.2.0

type AccountAccessListOptions struct {
	ProjectIDs []int64
	SandboxIDs []int64
	DomainIDs  []int64
}

AccountAccessListOptions filters a listing to accesses on the given resources. Leave it nil (or its fields empty) to list all accesses.

type AccountAccessPermissions added in v0.2.0

type AccountAccessPermissions struct {
	CanRead    bool `json:"can_read"`
	CanUpdate  bool `json:"can_update"`
	CanDestroy bool `json:"can_destroy"`
	CanLeave   bool `json:"can_leave"`
}

AccountAccessPermissions reports what the caller may do with an access.

type AccountAccessResource added in v0.2.0

type AccountAccessResource struct {
	ResourceID int64 `json:"resource_id"`
	// ResourceType identifies the kind of resource.
	ResourceType string `json:"resource_type"`
	// AccessLevel is the level granted on the resource.
	AccessLevel int `json:"access_level"`
}

AccountAccessResource is a resource the specifier can access and at what level.

type AccountAccessSpecifier added in v0.2.0

type AccountAccessSpecifier struct {
	ID                             int64  `json:"id"`
	Email                          string `json:"email,omitempty"`
	Name                           string `json:"name,omitempty"`
	TwoFactorAuthenticationEnabled *bool  `json:"two_factor_authentication_enabled,omitempty"`
	AuthorName                     string `json:"author_name,omitempty"`
	Token                          string `json:"token,omitempty"`
	ExpiresAt                      string `json:"expires_at,omitempty"`
}

AccountAccessSpecifier describes the entity that holds the access. Which fields are set depends on the specifier type: users and invites carry Email, while API tokens carry AuthorName, Token, and ExpiresAt.

type AccountAccessesService added in v0.2.0

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

AccountAccessesService lists and removes account accesses: the users, invites, and API tokens that hold permissions on an account.

func (*AccountAccessesService) Delete added in v0.2.0

func (s *AccountAccessesService) Delete(ctx context.Context, accessID int64) (*Response, error)

Delete removes an account access by ID. For a user specifier it removes the user's permissions; for an invite or token it removes the specifier too.

func (*AccountAccessesService) List added in v0.2.0

List returns account accesses whose specifier is a user or invite, filtered by opts (pass nil for no filters). Requires account admin or owner permissions.

type AccountsService added in v0.2.0

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

AccountsService lists the Mailtrap accounts the API token can access.

func (*AccountsService) List added in v0.2.0

func (s *AccountsService) List(ctx context.Context) ([]*Account, *Response, error)

List returns the accounts the token can access. An organization-level token returns every account in the organization.

type Address

type Address struct {
	Email string `json:"email"`
	Name  string `json:"name,omitempty"`
}

Address is an email address with an optional display name.

type Attachment

type Attachment struct {
	// Content is the base64-encoded file content.
	Content string `json:"content"`
	// Type is the MIME type, e.g. "text/csv".
	Type string `json:"type,omitempty"`
	// Filename is the attachment's file name.
	Filename string `json:"filename"`
	// Disposition is "attachment" (default) or "inline".
	Disposition string `json:"disposition,omitempty"`
	// ContentID references an inline attachment from the HTML body.
	ContentID string `json:"content_id,omitempty"`
}

Attachment is a file attached to an outgoing email.

type AttachmentListOptions

type AttachmentListOptions struct {
	// Type filters by attachment type, e.g. "inline" or "attachment".
	Type string
}

AttachmentListOptions filters a sandbox message's attachments.

type BatchSendRequest

type BatchSendRequest struct {
	Base     *SendRequest  `json:"base,omitempty"`
	Requests []SendRequest `json:"requests"`
}

BatchSendRequest sends many emails in one call. Base holds fields shared by every message in Requests; per-request fields override Base.

type BatchSendResponse

type BatchSendResponse struct {
	Success   bool                    `json:"success"`
	Errors    []string                `json:"errors,omitempty"`
	Responses []BatchSendResponseItem `json:"responses"`
}

BatchSendResponse is the result of a batch send; Responses is aligned with the request order.

type BatchSendResponseItem

type BatchSendResponseItem struct {
	Success    bool     `json:"success"`
	MessageIDs []string `json:"message_ids,omitempty"`
	Errors     []string `json:"errors,omitempty"`
}

BatchSendResponseItem is the per-message result within a batch send.

type BillingCounter added in v0.2.0

type BillingCounter struct {
	Current int `json:"current"`
	Limit   int `json:"limit"`
}

BillingCounter is a used/limit pair.

type BillingCycle added in v0.2.0

type BillingCycle struct {
	CycleStart string `json:"cycle_start"`
	CycleEnd   string `json:"cycle_end"`
}

BillingCycle is the current billing period.

type BillingPlan added in v0.2.0

type BillingPlan struct {
	Name string `json:"name"`
}

BillingPlan names the active plan for a product.

type BillingProduct added in v0.2.0

type BillingProduct struct {
	Plan  *BillingPlan         `json:"plan"`
	Usage *BillingUsageMetrics `json:"usage"`
}

BillingProduct is one product's plan and usage.

type BillingService added in v0.2.0

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

BillingService reads the account's current billing-cycle usage.

func (*BillingService) Usage added in v0.2.0

Usage returns the account's usage for the current billing cycle across Sandbox, Email Sending, and Email Marketing.

type BillingUsage added in v0.2.0

type BillingUsage struct {
	Billing   *BillingCycle   `json:"billing"`
	Testing   *BillingProduct `json:"testing,omitempty"`
	Sending   *BillingProduct `json:"sending,omitempty"`
	Marketing *BillingProduct `json:"marketing,omitempty"`
}

BillingUsage reports plan and usage for each product in the current cycle. A product is nil when the account has no plan for it.

type BillingUsageMetrics added in v0.2.0

type BillingUsageMetrics struct {
	SentMessagesCount      *BillingCounter `json:"sent_messages_count,omitempty"`
	ForwardedMessagesCount *BillingCounter `json:"forwarded_messages_count,omitempty"`
}

BillingUsageMetrics counts messages used against the plan limit. ForwardedMessagesCount is only set for the Sandbox (testing) product.

type CategoryStats

type CategoryStats struct {
	Category string       `json:"category"`
	Stats    SendingStats `json:"stats"`
}

CategoryStats holds sending stats for a single category.

type Client

type Client struct {

	// Projects manages sandbox projects.
	Projects *ProjectsService
	// Sandboxes manages sandboxes (testing inboxes) and their actions.
	Sandboxes *SandboxesService
	// SandboxMessages manages messages captured by a sandbox.
	SandboxMessages *SandboxMessagesService
	// SandboxAttachments reads attachments of sandbox messages.
	SandboxAttachments *SandboxAttachmentsService

	// SendingDomains manages sending domains and their compliance settings.
	SendingDomains *SendingDomainsService
	// Suppressions manages the account's do-not-send list.
	Suppressions *SuppressionsService
	// Stats reads aggregated email sending statistics.
	Stats *StatsService
	// EmailLogs reads the account's email logs and delivery events.
	EmailLogs *EmailLogsService
	// Webhooks manages account webhooks.
	Webhooks *WebhooksService
	// EmailTemplates manages the account's email templates.
	EmailTemplates *EmailTemplatesService

	// Accounts lists the accounts the token can access.
	Accounts *AccountsService
	// AccountAccesses lists and removes user, invite, and token accesses.
	AccountAccesses *AccountAccessesService
	// Permissions lists account resources and bulk-updates access permissions.
	Permissions *PermissionsService
	// APITokens manages the account's API tokens.
	APITokens *APITokensService
	// Billing reads current billing-cycle usage.
	Billing *BillingService
	// SubAccounts lists and creates sub-accounts within an organization.
	SubAccounts *SubAccountsService

	// Contacts manages email marketing contacts.
	Contacts *ContactsService
	// ContactEvents records custom events for contacts.
	ContactEvents *ContactEventsService
	// ContactLists manages contact lists.
	ContactLists *ContactListsService
	// ContactFields manages custom contact fields.
	ContactFields *ContactFieldsService
	// ContactImports bulk-imports contacts via asynchronous jobs.
	ContactImports *ContactImportsService
	// ContactExports exports contacts via asynchronous jobs.
	ContactExports *ContactExportsService
	// contains filtered or unexported fields
}

Client manages communication with the Mailtrap API.

func NewClient

func NewClient(token string, opts ...Option) (*Client, error)

NewClient returns a Mailtrap API client authenticated with the given token. The token is required; everything else is set through options.

func (*Client) Send

func (c *Client) Send(ctx context.Context, req *SendRequest) (*SendResponse, *Response, error)

Send sends an email. The destination is chosen from the client's configuration: the sandbox in sandbox mode (captured, not delivered to real recipients), the bulk host in bulk mode, or the transactional host otherwise.

func (*Client) SendBatch

func (c *Client) SendBatch(ctx context.Context, req *BatchSendRequest) (*BatchSendResponse, *Response, error)

SendBatch sends a batch of emails in a single request, routed like Send.

type CompanyInfo

type CompanyInfo struct {
	Name              string `json:"name"`
	Address           string `json:"address"`
	City              string `json:"city"`
	Country           string `json:"country"`
	Phone             string `json:"phone"`
	ZipCode           string `json:"zip_code"`
	PrivacyPolicyURL  string `json:"privacy_policy_url"`
	TermsOfServiceURL string `json:"terms_of_service_url"`
	WebsiteURL        string `json:"website_url"`
	// InfoLevel is "business" or "individual".
	InfoLevel string `json:"info_level"`
}

CompanyInfo is the sender's company information used for compliance review.

type CompanyInfoRequest

type CompanyInfoRequest struct {
	Name              string `json:"name,omitempty"`
	Address           string `json:"address,omitempty"`
	City              string `json:"city,omitempty"`
	Country           string `json:"country,omitempty"`
	ZipCode           string `json:"zip_code,omitempty"`
	WebsiteURL        string `json:"website_url,omitempty"`
	Phone             string `json:"phone,omitempty"`
	PrivacyPolicyURL  string `json:"privacy_policy_url,omitempty"`
	TermsOfServiceURL string `json:"terms_of_service_url,omitempty"`
	// InfoLevel is "business" or "individual".
	InfoLevel string `json:"info_level,omitempty"`
}

CompanyInfoRequest is the payload for creating or updating company info. On create, name, address, city, country, zip_code, and website_url are required; on update, every field is optional and only the set fields are changed.

type Contact added in v0.2.0

type Contact struct {
	// ID is the contact's UUID.
	ID    string `json:"id"`
	Email string `json:"email"`
	// Fields maps custom field merge tags to scalar values.
	Fields  map[string]any `json:"fields,omitempty"`
	ListIDs []int64        `json:"list_ids,omitempty"`
	// Status is the subscription status.
	Status string `json:"status,omitempty"`
	// CreatedAt and UpdatedAt are Unix timestamps in milliseconds.
	CreatedAt int64 `json:"created_at,omitempty"`
	UpdatedAt int64 `json:"updated_at,omitempty"`
}

Contact is an email marketing contact.

type ContactEvent added in v0.2.0

type ContactEvent struct {
	ContactID    string `json:"contact_id"`
	ContactEmail string `json:"contact_email"`
	Name         string `json:"name"`
	// Params maps event parameter names to scalar values.
	Params map[string]any `json:"params,omitempty"`
}

ContactEvent is a custom event recorded against a contact.

type ContactEventsService added in v0.2.0

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

ContactEventsService records custom events for a contact.

func (*ContactEventsService) Create added in v0.2.0

Create records an event for the contact identified by UUID or email.

type ContactExport added in v0.2.0

type ContactExport struct {
	ID        int64  `json:"id"`
	Status    string `json:"status"`
	CreatedAt string `json:"created_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
	// URL points to the exported file; nil until the export is finished.
	URL *string `json:"url,omitempty"`
}

ContactExport is an asynchronous export job. URL is set only once Status is "finished".

type ContactExportFilter added in v0.2.0

type ContactExportFilter struct {
	Name     string `json:"name"`
	Operator string `json:"operator"`
	Value    any    `json:"value"`
}

ContactExportFilter narrows an export. Name selects the field (see the ContactExportFilter* constants), Operator is "equal", and Value is a []int64 of list IDs (for list_id) or a subscription-status string.

type ContactExportsService added in v0.2.0

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

ContactExportsService exports contacts via asynchronous jobs.

func (*ContactExportsService) Create added in v0.2.0

Create starts an asynchronous export of contacts matching filters (pass nil to export all). Poll Get with the returned ID until Status is "finished".

func (*ContactExportsService) Get added in v0.2.0

Get returns the status of a contact export by ID, including the download URL once finished.

type ContactField added in v0.2.0

type ContactField struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	// DataType is the field's value type.
	DataType string `json:"data_type"`
	// MergeTag personalizes campaigns with the field's per-contact value.
	MergeTag string `json:"merge_tag"`
}

ContactField is a custom field that can be set on contacts.

type ContactFieldsService added in v0.2.0

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

ContactFieldsService manages custom contact fields.

func (*ContactFieldsService) Create added in v0.2.0

Create adds a contact field.

func (*ContactFieldsService) Delete added in v0.2.0

func (s *ContactFieldsService) Delete(ctx context.Context, fieldID int64) (*Response, error)

Delete removes a contact field by ID.

func (*ContactFieldsService) Get added in v0.2.0

Get returns a contact field by ID.

func (*ContactFieldsService) List added in v0.2.0

List returns all contact fields.

func (*ContactFieldsService) Update added in v0.2.0

Update changes a contact field's name and merge tag.

type ContactImport added in v0.2.0

type ContactImport struct {
	ID                     int64  `json:"id"`
	Status                 string `json:"status"`
	CreatedContactsCount   int64  `json:"created_contacts_count,omitempty"`
	UpdatedContactsCount   int64  `json:"updated_contacts_count,omitempty"`
	ContactsOverLimitCount int64  `json:"contacts_over_limit_count,omitempty"`
}

ContactImport is an asynchronous bulk-import job. The count fields are populated only once Status is "finished".

type ContactImportsService added in v0.2.0

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

ContactImportsService bulk-imports contacts via asynchronous jobs.

func (*ContactImportsService) Create added in v0.2.0

Create starts an asynchronous import of the given contacts. Poll Get with the returned ID until Status is "finished" or "failed".

func (*ContactImportsService) Get added in v0.2.0

Get returns the status of a contact import by ID.

type ContactList added in v0.2.0

type ContactList struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

ContactList is a named list that groups contacts.

type ContactListsService added in v0.2.0

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

ContactListsService manages contact lists.

func (*ContactListsService) Create added in v0.2.0

func (s *ContactListsService) Create(ctx context.Context, name string) (*ContactList, *Response, error)

Create adds a contact list with the given name.

func (*ContactListsService) Delete added in v0.2.0

func (s *ContactListsService) Delete(ctx context.Context, listID int64) (*Response, error)

Delete removes a contact list by ID.

func (*ContactListsService) Get added in v0.2.0

Get returns a contact list by ID.

func (*ContactListsService) List added in v0.2.0

List returns all contact lists.

func (*ContactListsService) Update added in v0.2.0

func (s *ContactListsService) Update(ctx context.Context, listID int64, name string) (*ContactList, *Response, error)

Update renames a contact list.

type ContactUpsert added in v0.2.0

type ContactUpsert struct {
	// Action is "created" or "updated".
	Action  string   `json:"action"`
	Contact *Contact `json:"data"`
}

ContactUpsert is the result of Update: the contact plus whether it was created or updated.

type ContactsService added in v0.2.0

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

ContactsService manages email marketing contacts.

func (*ContactsService) Create added in v0.2.0

Create adds a contact.

func (*ContactsService) Delete added in v0.2.0

func (s *ContactsService) Delete(ctx context.Context, identifier string) (*Response, error)

Delete removes a contact by UUID or email.

func (*ContactsService) Get added in v0.2.0

func (s *ContactsService) Get(ctx context.Context, identifier string) (*Contact, *Response, error)

Get returns a contact by UUID or email.

func (*ContactsService) Update added in v0.2.0

func (s *ContactsService) Update(ctx context.Context, identifier string, req *UpdateContactRequest) (*ContactUpsert, *Response, error)

Update creates or updates (upserts) the contact identified by UUID or email, reporting which action was taken.

type CreateAPITokenRequest added in v0.2.0

type CreateAPITokenRequest struct {
	Name      string                `json:"name"`
	Resources []*APITokenPermission `json:"resources,omitempty"`
}

CreateAPITokenRequest is the payload for creating an API token. Name is required.

type CreateContactEventRequest added in v0.2.0

type CreateContactEventRequest struct {
	Name   string         `json:"name"`
	Params map[string]any `json:"params,omitempty"`
}

CreateContactEventRequest is the payload for recording an event. Name is required (max 255 characters).

type CreateContactFieldRequest added in v0.2.0

type CreateContactFieldRequest struct {
	Name     string `json:"name"`
	DataType string `json:"data_type"`
	MergeTag string `json:"merge_tag"`
}

CreateContactFieldRequest is the payload for creating a contact field. All fields are required.

type CreateContactRequest added in v0.2.0

type CreateContactRequest struct {
	Email   string         `json:"email"`
	Fields  map[string]any `json:"fields,omitempty"`
	ListIDs []int64        `json:"list_ids,omitempty"`
}

CreateContactRequest is the payload for creating a contact. Email is required.

type CreateSuppressionRequest

type CreateSuppressionRequest struct {
	Email         string `json:"email"`
	DomainID      int64  `json:"domain_id"`
	SendingStream string `json:"sending_stream"`
	Type          string `json:"type,omitempty"`
}

CreateSuppressionRequest is the payload for suppressing an address. Type is optional and defaults to "manual import".

type CreateWebhookRequest

type CreateWebhookRequest struct {
	URL            string   `json:"url"`
	WebhookType    string   `json:"webhook_type"`
	Active         *bool    `json:"active,omitempty"`
	PayloadFormat  string   `json:"payload_format,omitempty"`
	SendingStream  string   `json:"sending_stream,omitempty"`
	EventTypes     []string `json:"event_types,omitempty"`
	DomainID       *int64   `json:"domain_id,omitempty"`
	InboundInboxID *int64   `json:"inbound_inbox_id,omitempty"`
}

CreateWebhookRequest is the payload for creating a webhook. URL and WebhookType are required; the rest are optional (Active defaults to true).

type DNSRecord

type DNSRecord struct {
	Key    string `json:"key"`
	Domain string `json:"domain"`
	Name   string `json:"name"`
	Status string `json:"status"`
	Type   string `json:"type"`
	Value  string `json:"value"`
}

DNSRecord is one DNS record a domain must publish for authentication.

type DateStats

type DateStats struct {
	Date  string       `json:"date"`
	Stats SendingStats `json:"stats"`
}

DateStats holds sending stats for a single date.

type DomainStats

type DomainStats struct {
	DomainID int64        `json:"domain_id"`
	Stats    SendingStats `json:"stats"`
}

DomainStats holds sending stats for a single domain.

type EmailLogMessage

type EmailLogMessage struct {
	MessageID string `json:"message_id"`
	// Status is the delivery status of the message.
	Status            string         `json:"status"`
	Subject           string         `json:"subject"`
	From              string         `json:"from"`
	To                string         `json:"to"`
	SentAt            string         `json:"sent_at"`
	ClientIP          string         `json:"client_ip"`
	Category          string         `json:"category"`
	CustomVariables   map[string]any `json:"custom_variables"`
	SendingStream     string         `json:"sending_stream"`
	DomainID          int64          `json:"domain_id"`
	TemplateID        *int64         `json:"template_id"`
	TemplateVariables map[string]any `json:"template_variables"`
	OpensCount        int64          `json:"opens_count"`
	ClicksCount       int64          `json:"clicks_count"`
	// RawMessageURL is a temporary signed URL to the raw .eml (Get only).
	RawMessageURL string `json:"raw_message_url,omitempty"`
	// Events is the delivery-lifecycle history (Get only).
	Events []MessageEvent `json:"events,omitempty"`
}

EmailLogMessage is a logged message. List populates the summary fields; Get also fills RawMessageURL and Events.

type EmailLogsList

type EmailLogsList struct {
	Messages       []*EmailLogMessage `json:"messages"`
	TotalCount     int64              `json:"total_count"`
	NextPageCursor string             `json:"next_page_cursor"`
}

EmailLogsList is a page of email logs. NextPageCursor is empty on the last page.

type EmailLogsListOptions

type EmailLogsListOptions struct {
	// SearchAfter is the NextPageCursor from a previous response.
	SearchAfter string
	SentAfter   string
	SentBefore  string
	Filters     map[string]LogFilter
}

EmailLogsListOptions filters and paginates an email-logs listing. Filters maps a field name (e.g. "to", "status", "category", "sending_domain_id") to its filter; SentAfter/SentBefore bound sent_at (ISO 8601).

type EmailLogsService

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

EmailLogsService reads the account's email logs (sent messages and their delivery events).

func (*EmailLogsService) All

All iterates every email log matching opts, following the cursor across pages. Iteration stops at the first error, yielded once.

func (*EmailLogsService) Get

func (s *EmailLogsService) Get(ctx context.Context, messageID string) (*EmailLogMessage, *Response, error)

Get returns a single email log message by its UUID, including its events.

func (*EmailLogsService) List

List returns a page of email logs matching opts, ordered by sent_at descending. Follow EmailLogsList.NextPageCursor with SearchAfter for the next page, or use All to iterate every match.

type EmailServiceProviderStats

type EmailServiceProviderStats struct {
	EmailServiceProvider string       `json:"email_service_provider"`
	Stats                SendingStats `json:"stats"`
}

EmailServiceProviderStats holds sending stats for a single ESP.

type EmailTemplate

type EmailTemplate struct {
	ID        int64  `json:"id"`
	UUID      string `json:"uuid"`
	Name      string `json:"name"`
	Category  string `json:"category"`
	Subject   string `json:"subject"`
	BodyText  string `json:"body_text,omitempty"`
	BodyHTML  string `json:"body_html,omitempty"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

EmailTemplate is a reusable email template.

type EmailTemplateRequest

type EmailTemplateRequest struct {
	Name     string `json:"name,omitempty"`
	Category string `json:"category,omitempty"`
	Subject  string `json:"subject,omitempty"`
	BodyText string `json:"body_text,omitempty"`
	BodyHTML string `json:"body_html,omitempty"`
}

EmailTemplateRequest is the payload for creating or updating a template. On create, Name, Subject, and Category are required; on update, only the set fields are changed.

type EmailTemplatesService

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

EmailTemplatesService manages the account's email templates.

func (*EmailTemplatesService) Create

Create adds an email template.

func (*EmailTemplatesService) Delete

func (s *EmailTemplatesService) Delete(ctx context.Context, templateID int64) (*Response, error)

Delete removes an email template by ID.

func (*EmailTemplatesService) Get

func (s *EmailTemplatesService) Get(ctx context.Context, templateID int64) (*EmailTemplate, *Response, error)

Get returns an email template by ID.

func (*EmailTemplatesService) List

List returns all email templates for the account.

func (*EmailTemplatesService) Update

Update changes the set fields of an email template.

type Error

type Error struct {
	// StatusCode is the HTTP status code.
	StatusCode int
	// Messages holds the human-readable error message(s) returned by the API.
	Messages []string
	// Body is the raw, undecoded response body.
	Body []byte
}

Error is the base Mailtrap API error for non-2xx responses. Status-specific wrappers embed it (e.g. RateLimitError, ValidationError); match with errors.As.

func (*Error) Error

func (e *Error) Error() string

type ForbiddenError

type ForbiddenError struct{ Err *Error }

ForbiddenError indicates the token is valid but lacks access to the resource (403).

func (*ForbiddenError) Error

func (e *ForbiddenError) Error() string

func (*ForbiddenError) Unwrap

func (e *ForbiddenError) Unwrap() error

Unwrap exposes the base *Error to errors.As/Is.

type HTMLAnalysisEmailClients

type HTMLAnalysisEmailClients struct {
	Desktop []string `json:"desktop"`
	Mobile  []string `json:"mobile"`
	Web     []string `json:"web"`
}

HTMLAnalysisEmailClients lists the clients affected by an HTML issue.

type HTMLAnalysisError

type HTMLAnalysisError struct {
	ErrorLine    int                      `json:"error_line"`
	RuleName     string                   `json:"rule_name"`
	EmailClients HTMLAnalysisEmailClients `json:"email_clients"`
}

HTMLAnalysisError is one HTML issue found by the analyzer.

type HTMLAnalysisReport

type HTMLAnalysisReport struct {
	Success string              `json:"success"`
	Errors  []HTMLAnalysisError `json:"errors"`
}

HTMLAnalysisReport is a message's HTML compatibility analysis.

type Host

type Host int

Host identifies one of Mailtrap's API hosts. Each request targets a specific host; values can be overridden (e.g. for tests) with WithBaseURL.

const (
	// HostGeneral is the account/sandbox management API (https://mailtrap.io).
	HostGeneral Host = iota
	// HostSend is the transactional sending API (https://send.api.mailtrap.io).
	HostSend
	// HostBulk is the bulk sending API (https://bulk.api.mailtrap.io).
	HostBulk
	// HostSandbox is the sandbox (testing) sending API (https://sandbox.api.mailtrap.io).
	HostSandbox
)

type ImportContact added in v0.2.0

type ImportContact struct {
	Email           string         `json:"email"`
	Fields          map[string]any `json:"fields,omitempty"`
	ListIDsIncluded []int64        `json:"list_ids_included,omitempty"`
	ListIDsExcluded []int64        `json:"list_ids_excluded,omitempty"`
}

ImportContact is one contact in a bulk import. ListIDsIncluded and ListIDsExcluded add and remove list memberships.

type LogFilter

type LogFilter struct {
	Operator string
	Values   []string
}

LogFilter is one email-logs filter: a comparison operator and its value(s). A single value is sent as a scalar and multiple values as an array; the empty and not_empty operators take no value.

type MessageEvent

type MessageEvent struct {
	EventType string              `json:"event_type"`
	CreatedAt string              `json:"created_at"`
	Details   MessageEventDetails `json:"details"`
}

MessageEvent is one delivery-lifecycle event. Which Details fields are populated depends on EventType.

type MessageEventDetails

type MessageEventDetails struct {
	SendingIP                    string `json:"sending_ip,omitempty"`
	RecipientMX                  string `json:"recipient_mx,omitempty"`
	EmailServiceProvider         string `json:"email_service_provider,omitempty"`
	EmailServiceProviderStatus   string `json:"email_service_provider_status,omitempty"`
	EmailServiceProviderResponse string `json:"email_service_provider_response,omitempty"`
	BounceCategory               string `json:"bounce_category,omitempty"`
	WebIPAddress                 string `json:"web_ip_address,omitempty"`
	ClickURL                     string `json:"click_url,omitempty"`
	SpamFeedbackType             string `json:"spam_feedback_type,omitempty"`
	RejectReason                 string `json:"reject_reason,omitempty"`
}

MessageEventDetails is the union of every event's detail fields; only those relevant to the event type are set.

type MessageListOptions

type MessageListOptions struct {
	// Search matches the subject, to_email, and to_name.
	Search string
	// Page selects a page of results (max 30 per page).
	Page int
	// LastID returns the page before this message ID, overriding Page.
	LastID int64
}

MessageListOptions are the filters for listing sandbox messages.

type NotFoundError added in v0.2.0

type NotFoundError struct{ Err *Error }

NotFoundError indicates the requested resource does not exist (404).

func (*NotFoundError) Error added in v0.2.0

func (e *NotFoundError) Error() string

func (*NotFoundError) Unwrap added in v0.2.0

func (e *NotFoundError) Unwrap() error

Unwrap exposes the base *Error to errors.As/Is.

type Option

type Option func(*Client) error

Option configures a Client in NewClient.

func WithBaseURL

func WithBaseURL(host Host, rawURL string) Option

WithBaseURL overrides the base URL for a host, primarily for testing against an httptest server.

func WithBulk

func WithBulk(enabled bool) Option

WithBulk routes Send/SendBatch to the bulk host. Mutually exclusive with WithSandbox.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets the underlying *http.Client. Its transport is wrapped to inject authentication, so a custom transport is preserved as the base.

func WithOrganizationID added in v0.2.0

func WithOrganizationID(organizationID int64) Option

WithOrganizationID sets the organization that SubAccounts operations target. A token can access a single organization, so it is configured once here rather than passed to every call. Required before using client.SubAccounts.

func WithSandbox

func WithSandbox(enabled bool) Option

WithSandbox routes Send/SendBatch to the sandbox host. Pair it with WithSandboxID. Toggle it from configuration to switch environments without changing call sites, e.g. WithSandbox(env != "production").

func WithSandboxID

func WithSandboxID(sandboxID int64) Option

WithSandboxID sets the sandbox that Send/SendBatch deliver to. Required in sandbox mode and ignored otherwise.

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent overrides the default User-Agent header.

type PermissionResource added in v0.2.0

type PermissionResource struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	// Type identifies the kind of resource.
	Type string `json:"type"`
	// AccessLevel is the token's access level for this resource.
	AccessLevel int                   `json:"access_level"`
	Resources   []*PermissionResource `json:"resources"`
}

PermissionResource is a node in the account's resource hierarchy (the account, projects, sandboxes, domains, and so on) that the token can administer.

type PermissionUpdate added in v0.2.0

type PermissionUpdate struct {
	ResourceID string `json:"resource_id"`
	// ResourceType identifies the kind of resource.
	ResourceType string `json:"resource_type"`
	// AccessLevel is the level to grant; leave empty when Destroy is true.
	AccessLevel string `json:"access_level,omitempty"`
	// Destroy removes the permission instead of creating or updating it.
	Destroy bool `json:"_destroy,omitempty"`
}

PermissionUpdate creates, updates, or removes one permission in a bulk update. A resource_type/resource_id pair that already exists is updated; otherwise it is created. Set Destroy to remove it instead.

type Permissions

type Permissions struct {
	CanRead    bool `json:"can_read"`
	CanUpdate  bool `json:"can_update"`
	CanDestroy bool `json:"can_destroy"`
	CanLeave   bool `json:"can_leave"`
}

Permissions describes the caller's permissions on a resource.

type PermissionsService added in v0.2.0

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

PermissionsService lists the resources a token can administer and updates the permissions attached to an account access.

func (*PermissionsService) BulkUpdate added in v0.2.0

func (s *PermissionsService) BulkUpdate(ctx context.Context, accessID int64, permissions []*PermissionUpdate) (*Response, error)

BulkUpdate creates, updates, or removes permissions for an account access in a single request.

func (*PermissionsService) Resources added in v0.2.0

Resources returns the account resources the token has admin access to, nested by hierarchy.

type Project

type Project struct {
	ID          int64        `json:"id"`
	Name        string       `json:"name"`
	ShareLinks  *ShareLinks  `json:"share_links,omitempty"`
	Sandboxes   []*Sandbox   `json:"sandboxes,omitempty"`
	Permissions *Permissions `json:"permissions,omitempty"`
}

Project groups sandboxes under a single container.

type ProjectsService

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

ProjectsService manages sandbox projects.

func (*ProjectsService) Create

func (s *ProjectsService) Create(ctx context.Context, name string) (*Project, *Response, error)

Create creates a project with the given name.

func (*ProjectsService) Delete

func (s *ProjectsService) Delete(ctx context.Context, projectID int64) (*Response, error)

Delete removes a project by ID.

func (*ProjectsService) Get

func (s *ProjectsService) Get(ctx context.Context, projectID int64) (*Project, *Response, error)

Get returns a project by ID.

func (*ProjectsService) List

func (s *ProjectsService) List(ctx context.Context) ([]*Project, *Response, error)

List returns all projects, with their sandboxes, accessible to the token.

func (*ProjectsService) Update

func (s *ProjectsService) Update(ctx context.Context, projectID int64, name string) (*Project, *Response, error)

Update renames a project.

type RateLimitError

type RateLimitError struct {
	Err *Error
	// RetryAfter is the delay advised by the Retry-After header, or 0 if absent.
	RetryAfter time.Duration
}

RateLimitError indicates the API rate limit was exceeded (429).

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap exposes the base *Error to errors.As/Is.

type Response

type Response struct {
	*http.Response

	// NextPage is the next page number for paginated list endpoints, or 0 when
	// there are no further pages.
	NextPage int
}

Response wraps the HTTP response with pagination metadata.

type SMTPInformation

type SMTPInformation struct {
	OK   bool                 `json:"ok"`
	Data *SMTPInformationData `json:"data,omitempty"`
}

SMTPInformation holds the SMTP-level details captured for a message.

type SMTPInformationData

type SMTPInformationData struct {
	MailFromAddr string `json:"mail_from_addr"`
	ClientIP     string `json:"client_ip"`
}

SMTPInformationData holds the envelope information of a captured message.

type Sandbox

type Sandbox struct {
	ID                      int64        `json:"id"`
	Name                    string       `json:"name"`
	Username                string       `json:"username"`
	Password                string       `json:"password"`
	MaxSize                 int64        `json:"max_size"`
	Status                  string       `json:"status"`
	EmailUsername           string       `json:"email_username"`
	EmailUsernameEnabled    bool         `json:"email_username_enabled"`
	SentMessagesCount       int64        `json:"sent_messages_count"`
	ForwardedMessagesCount  int64        `json:"forwarded_messages_count"`
	Used                    bool         `json:"used"`
	ForwardFromEmailAddress string       `json:"forward_from_email_address"`
	ProjectID               int64        `json:"project_id"`
	Domain                  string       `json:"domain"`
	POP3Domain              string       `json:"pop3_domain"`
	EmailDomain             string       `json:"email_domain"`
	APIDomain               string       `json:"api_domain"`
	EmailsCount             int64        `json:"emails_count"`
	EmailsUnreadCount       int64        `json:"emails_unread_count"`
	LastMessageSentAt       *string      `json:"last_message_sent_at"`
	SMTPPorts               []int        `json:"smtp_ports"`
	POP3Ports               []int        `json:"pop3_ports"`
	MaxMessageSize          int64        `json:"max_message_size"`
	Permissions             *Permissions `json:"permissions,omitempty"`
}

Sandbox is a testing inbox that captures emails sent to it instead of delivering them to real recipients.

type SandboxAttachment

type SandboxAttachment struct {
	ID                  int64  `json:"id"`
	MessageID           int64  `json:"message_id"`
	Filename            string `json:"filename"`
	AttachmentType      string `json:"attachment_type"`
	ContentType         string `json:"content_type"`
	ContentID           string `json:"content_id"`
	TransferEncoding    string `json:"transfer_encoding"`
	AttachmentSize      int64  `json:"attachment_size"`
	CreatedAt           string `json:"created_at"`
	UpdatedAt           string `json:"updated_at"`
	AttachmentHumanSize string `json:"attachment_human_size"`
	DownloadPath        string `json:"download_path"`
}

SandboxAttachment is a file attached to a sandbox message.

type SandboxAttachmentsService

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

SandboxAttachmentsService reads attachments of sandbox messages.

func (*SandboxAttachmentsService) Get

func (s *SandboxAttachmentsService) Get(ctx context.Context, sandboxID, messageID, attachmentID int64) (*SandboxAttachment, *Response, error)

Get returns a single attachment by ID.

func (*SandboxAttachmentsService) List

func (s *SandboxAttachmentsService) List(ctx context.Context, sandboxID, messageID int64, opts *AttachmentListOptions) ([]*SandboxAttachment, *Response, error)

List returns the attachments of a message.

type SandboxMessage

type SandboxMessage struct {
	ID              int64            `json:"id"`
	SandboxID       int64            `json:"sandbox_id"`
	Subject         string           `json:"subject"`
	SentAt          string           `json:"sent_at"`
	FromEmail       string           `json:"from_email"`
	FromName        string           `json:"from_name"`
	ToEmail         string           `json:"to_email"`
	ToName          string           `json:"to_name"`
	EmailSize       int64            `json:"email_size"`
	IsRead          bool             `json:"is_read"`
	CreatedAt       string           `json:"created_at"`
	UpdatedAt       string           `json:"updated_at"`
	HTMLBodySize    int64            `json:"html_body_size"`
	TextBodySize    int64            `json:"text_body_size"`
	HumanSize       string           `json:"human_size"`
	HTMLPath        string           `json:"html_path"`
	TxtPath         string           `json:"txt_path"`
	RawPath         string           `json:"raw_path"`
	DownloadPath    string           `json:"download_path"`
	HTMLSourcePath  string           `json:"html_source_path"`
	SMTPInformation *SMTPInformation `json:"smtp_information,omitempty"`
}

SandboxMessage is an email captured by a sandbox.

type SandboxMessagesService

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

SandboxMessagesService manages messages captured by a sandbox.

func (*SandboxMessagesService) All

All iterates every message in a sandbox, fetching pages on demand. Iteration stops at the first error, which is yielded once.

func (*SandboxMessagesService) Delete

func (s *SandboxMessagesService) Delete(ctx context.Context, sandboxID, messageID int64) (*SandboxMessage, *Response, error)

Delete removes a message, returning the deleted message.

func (*SandboxMessagesService) EML

func (s *SandboxMessagesService) EML(ctx context.Context, sandboxID, messageID int64) ([]byte, *Response, error)

EML returns the message in .eml format.

func (*SandboxMessagesService) Forward

func (s *SandboxMessagesService) Forward(ctx context.Context, sandboxID, messageID int64, email string) (*Response, error)

Forward forwards a message to an email address that has been confirmed by its recipient in advance.

func (*SandboxMessagesService) Get

func (s *SandboxMessagesService) Get(ctx context.Context, sandboxID, messageID int64) (*SandboxMessage, *Response, error)

Get returns a message by ID.

func (*SandboxMessagesService) HTML

func (s *SandboxMessagesService) HTML(ctx context.Context, sandboxID, messageID int64) ([]byte, *Response, error)

HTML returns the formatted HTML body of a message.

func (*SandboxMessagesService) HTMLAnalysis

func (s *SandboxMessagesService) HTMLAnalysis(ctx context.Context, sandboxID, messageID int64) (*HTMLAnalysisReport, *Response, error)

HTMLAnalysis returns the HTML compatibility analysis of a message.

func (*SandboxMessagesService) HTMLSource

func (s *SandboxMessagesService) HTMLSource(ctx context.Context, sandboxID, messageID int64) ([]byte, *Response, error)

HTMLSource returns the HTML source of a message.

func (*SandboxMessagesService) Headers

func (s *SandboxMessagesService) Headers(ctx context.Context, sandboxID, messageID int64) (map[string]string, *Response, error)

Headers returns the mail headers of a message.

func (*SandboxMessagesService) List

List returns a page of messages in a sandbox. Response.NextPage is set when a full page is returned and more results are likely available.

func (*SandboxMessagesService) Raw

func (s *SandboxMessagesService) Raw(ctx context.Context, sandboxID, messageID int64) ([]byte, *Response, error)

Raw returns the raw MIME source of a message.

func (*SandboxMessagesService) SpamReport

func (s *SandboxMessagesService) SpamReport(ctx context.Context, sandboxID, messageID int64) (*SpamReport, *Response, error)

SpamReport returns the spam analysis of a message.

func (*SandboxMessagesService) Text

func (s *SandboxMessagesService) Text(ctx context.Context, sandboxID, messageID int64) ([]byte, *Response, error)

Text returns the plain-text body of a message.

func (*SandboxMessagesService) Update

func (s *SandboxMessagesService) Update(ctx context.Context, sandboxID, messageID int64, isRead bool) (*SandboxMessage, *Response, error)

Update sets a message's read state, returning the updated message.

type SandboxUpdateRequest

type SandboxUpdateRequest struct {
	Name          string `json:"name,omitempty"`
	EmailUsername string `json:"email_username,omitempty"`
}

SandboxUpdateRequest holds the editable attributes of a sandbox; empty fields are omitted from the request.

type SandboxesService

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

SandboxesService manages sandboxes (testing inboxes) and their actions.

func (*SandboxesService) Clean

func (s *SandboxesService) Clean(ctx context.Context, sandboxID int64) (*Sandbox, *Response, error)

Clean deletes all messages from a sandbox.

func (*SandboxesService) Create

func (s *SandboxesService) Create(ctx context.Context, projectID int64, name string) (*Sandbox, *Response, error)

Create creates a sandbox with the given name in a project.

func (*SandboxesService) Delete

func (s *SandboxesService) Delete(ctx context.Context, sandboxID int64) (*Sandbox, *Response, error)

Delete removes a sandbox and all its messages, returning the deleted sandbox.

func (*SandboxesService) Get

func (s *SandboxesService) Get(ctx context.Context, sandboxID int64) (*Sandbox, *Response, error)

Get returns a sandbox by ID.

func (*SandboxesService) List

func (s *SandboxesService) List(ctx context.Context) ([]*Sandbox, *Response, error)

List returns all sandboxes accessible to the token.

func (*SandboxesService) MarkAllRead

func (s *SandboxesService) MarkAllRead(ctx context.Context, sandboxID int64) (*Sandbox, *Response, error)

MarkAllRead marks every message in a sandbox as read.

func (*SandboxesService) ResetCredentials

func (s *SandboxesService) ResetCredentials(ctx context.Context, sandboxID int64) (*Sandbox, *Response, error)

ResetCredentials regenerates the sandbox's SMTP credentials.

func (*SandboxesService) ResetEmailAddress

func (s *SandboxesService) ResetEmailAddress(ctx context.Context, sandboxID int64) (*Sandbox, *Response, error)

ResetEmailAddress resets the username of the sandbox's email address.

func (*SandboxesService) ToggleEmailAddress

func (s *SandboxesService) ToggleEmailAddress(ctx context.Context, sandboxID int64) (*Sandbox, *Response, error)

ToggleEmailAddress enables or disables the sandbox's email address.

func (*SandboxesService) Update

func (s *SandboxesService) Update(ctx context.Context, sandboxID int64, req *SandboxUpdateRequest) (*Sandbox, *Response, error)

Update changes a sandbox's name and/or email username.

type SendRequest

type SendRequest struct {
	From              Address           `json:"from"`
	To                []Address         `json:"to,omitempty"`
	Cc                []Address         `json:"cc,omitempty"`
	Bcc               []Address         `json:"bcc,omitempty"`
	ReplyTo           *Address          `json:"reply_to,omitempty"`
	Subject           string            `json:"subject,omitempty"`
	Text              string            `json:"text,omitempty"`
	HTML              string            `json:"html,omitempty"`
	Category          string            `json:"category,omitempty"`
	Attachments       []Attachment      `json:"attachments,omitempty"`
	Headers           map[string]string `json:"headers,omitempty"`
	CustomVariables   map[string]any    `json:"custom_variables,omitempty"`
	TemplateUUID      string            `json:"template_uuid,omitempty"`
	TemplateVariables map[string]any    `json:"template_variables,omitempty"`
}

SendRequest is an email to send. Provide Text, HTML, or both, or set TemplateUUID with TemplateVariables to send from a template.

type SendResponse

type SendResponse struct {
	Success    bool     `json:"success"`
	MessageIDs []string `json:"message_ids"`
}

SendResponse is the result of a successful send.

type SendingDomain

type SendingDomain struct {
	ID                          int64                     `json:"id"`
	DomainName                  string                    `json:"domain_name"`
	Demo                        bool                      `json:"demo"`
	ComplianceStatus            string                    `json:"compliance_status"`
	DNSVerified                 bool                      `json:"dns_verified"`
	DNSVerifiedAt               string                    `json:"dns_verified_at"`
	DNSRecords                  []DNSRecord               `json:"dns_records"`
	OpenTrackingEnabled         bool                      `json:"open_tracking_enabled"`
	ClickTrackingEnabled        bool                      `json:"click_tracking_enabled"`
	AutoUnsubscribeLinkEnabled  bool                      `json:"auto_unsubscribe_link_enabled"`
	CustomDomainTrackingEnabled bool                      `json:"custom_domain_tracking_enabled"`
	HealthAlertsEnabled         bool                      `json:"health_alerts_enabled"`
	CriticalAlertsEnabled       bool                      `json:"critical_alerts_enabled"`
	AlertRecipientEmail         string                    `json:"alert_recipient_email"`
	Permissions                 *SendingDomainPermissions `json:"permissions,omitempty"`
}

SendingDomain is a domain used for email authentication and sending.

type SendingDomainPermissions

type SendingDomainPermissions struct {
	CanRead    bool `json:"can_read"`
	CanUpdate  bool `json:"can_update"`
	CanDestroy bool `json:"can_destroy"`
}

SendingDomainPermissions describes the caller's permissions on a domain.

type SendingDomainsService

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

SendingDomainsService manages sending domains and their compliance settings.

func (*SendingDomainsService) CompanyInfo

func (s *SendingDomainsService) CompanyInfo(ctx context.Context, domainID int64) (*CompanyInfo, *Response, error)

CompanyInfo returns the company information attached to a domain.

func (*SendingDomainsService) Create

func (s *SendingDomainsService) Create(ctx context.Context, domainName string) (*SendingDomain, *Response, error)

Create adds a sending domain. After creation, publish the returned DNS records and verify them before sending in production.

func (*SendingDomainsService) CreateCompanyInfo

func (s *SendingDomainsService) CreateCompanyInfo(ctx context.Context, domainID int64, req *CompanyInfoRequest) (*CompanyInfo, *Response, error)

CreateCompanyInfo sets the company information for a domain.

func (*SendingDomainsService) Delete

func (s *SendingDomainsService) Delete(ctx context.Context, domainID int64) (*Response, error)

Delete removes a sending domain by ID.

func (*SendingDomainsService) Get

Get returns a sending domain by ID.

func (*SendingDomainsService) List

List returns all sending domains and their verification status.

func (*SendingDomainsService) SendSetupInstructions

func (s *SendingDomainsService) SendSetupInstructions(ctx context.Context, domainID int64, email string) (*Response, error)

SendSetupInstructions emails the domain's DNS setup instructions to an address.

func (*SendingDomainsService) Update

Update changes a domain's tracking settings.

func (*SendingDomainsService) UpdateCompanyInfo

func (s *SendingDomainsService) UpdateCompanyInfo(ctx context.Context, domainID int64, req *CompanyInfoRequest) (*CompanyInfo, *Response, error)

UpdateCompanyInfo changes the set fields of a domain's company information.

type SendingStats

type SendingStats struct {
	DeliveryCount int64   `json:"delivery_count"`
	DeliveryRate  float64 `json:"delivery_rate"`
	BounceCount   int64   `json:"bounce_count"`
	BounceRate    float64 `json:"bounce_rate"`
	OpenCount     int64   `json:"open_count"`
	OpenRate      float64 `json:"open_rate"`
	ClickCount    int64   `json:"click_count"`
	ClickRate     float64 `json:"click_rate"`
	SpamCount     int64   `json:"spam_count"`
	SpamRate      float64 `json:"spam_rate"`
}

SendingStats holds delivery, bounce, open, click, and spam counts and rates for a period. Rates are fractions in the range 0..1.

type ShareLinks struct {
	Admin  string `json:"admin"`
	Viewer string `json:"viewer"`
}

ShareLinks holds a project's public share URLs.

type SpamReport

type SpamReport struct {
	ResponseCode    int                `json:"ResponseCode"`
	ResponseMessage string             `json:"ResponseMessage"`
	ResponseVersion string             `json:"ResponseVersion"`
	Score           float64            `json:"Score"`
	Spam            bool               `json:"Spam"`
	Threshold       float64            `json:"Threshold"`
	Details         []SpamReportDetail `json:"Details"`
}

SpamReport is a message's spam analysis.

type SpamReportDetail

type SpamReportDetail struct {
	Pts         float64 `json:"Pts"`
	RuleName    string  `json:"RuleName"`
	Description string  `json:"Description"`
}

SpamReportDetail is one rule hit in a SpamReport.

type StatsOptions

type StatsOptions struct {
	StartDate             string
	EndDate               string
	SendingDomainIDs      []int64
	SendingStreams        []string
	Categories            []string
	EmailServiceProviders []string
}

StatsOptions filters a stats query. StartDate and EndDate (YYYY-MM-DD) are required; the remaining fields narrow the results and may be omitted.

type StatsService

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

StatsService reads aggregated email sending statistics.

func (*StatsService) ByCategory

func (s *StatsService) ByCategory(ctx context.Context, opts *StatsOptions) ([]*CategoryStats, *Response, error)

ByCategory returns sending stats grouped by category.

func (*StatsService) ByDate

func (s *StatsService) ByDate(ctx context.Context, opts *StatsOptions) ([]*DateStats, *Response, error)

ByDate returns sending stats grouped by date.

func (*StatsService) ByDomain

func (s *StatsService) ByDomain(ctx context.Context, opts *StatsOptions) ([]*DomainStats, *Response, error)

ByDomain returns sending stats grouped by domain.

func (*StatsService) ByEmailServiceProvider

func (s *StatsService) ByEmailServiceProvider(ctx context.Context, opts *StatsOptions) ([]*EmailServiceProviderStats, *Response, error)

ByEmailServiceProvider returns sending stats grouped by ESP.

func (*StatsService) Get

Get returns the account's aggregated sending stats for the period.

type SubAccount added in v0.2.0

type SubAccount struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

SubAccount is an account within an organization.

type SubAccountsService added in v0.2.0

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

SubAccountsService lists and creates the sub-accounts of an organization. These endpoints require an organization token with sub-account management permission.

func (*SubAccountsService) Create added in v0.2.0

func (s *SubAccountsService) Create(ctx context.Context, name string) (*SubAccount, *Response, error)

Create adds a sub-account with the given name under the organization set with WithOrganizationID.

func (*SubAccountsService) List added in v0.2.0

List returns the sub-accounts of the organization set with WithOrganizationID.

type Suppression

type Suppression struct {
	ID string `json:"id"`
	// Type is the reason for the suppression.
	Type      string `json:"type"`
	CreatedAt string `json:"created_at"`
	Email     string `json:"email"`
	// SendingStream is the stream the suppression applies to.
	SendingStream          string `json:"sending_stream"`
	DomainName             string `json:"domain_name"`
	MessageBounceCategory  string `json:"message_bounce_category"`
	MessageCategory        string `json:"message_category"`
	MessageClientIP        string `json:"message_client_ip"`
	MessageCreatedAt       string `json:"message_created_at"`
	MessageESPResponse     string `json:"message_esp_response"`
	MessageESPServerType   string `json:"message_esp_server_type"`
	MessageOutgoingIP      string `json:"message_outgoing_ip"`
	MessageRecipientMXName string `json:"message_recipient_mx_name"`
	MessageSenderEmail     string `json:"message_sender_email"`
	MessageSubject         string `json:"message_subject"`
}

Suppression is a single suppressed recipient and the message that caused it.

type SuppressionListOptions

type SuppressionListOptions struct {
	// Email filters by exact address (case-insensitive).
	Email string
	// StartTime and EndTime bound the created_at timestamp (ISO 8601).
	StartTime string
	EndTime   string
	// LastID returns suppressions after this one, for cursor-based pagination.
	LastID string
}

SuppressionListOptions filters a suppression listing. The endpoint returns up to 1000 suppressions per request; page through larger lists by passing the last returned suppression's ID as LastID.

type SuppressionsService

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

SuppressionsService manages the account's suppression list: addresses that Mailtrap will not send to because of bounces, complaints, or unsubscribes.

func (*SuppressionsService) Create

Create suppresses an address, returning the created suppression.

func (*SuppressionsService) Delete

func (s *SuppressionsService) Delete(ctx context.Context, suppressionID string) (*Suppression, *Response, error)

Delete removes a suppression by ID, returning the deleted suppression. Mailtrap will send to the address again unless it is suppressed anew.

func (*SuppressionsService) List

List returns suppressions matching opts (pass nil for no filters).

type UnauthorizedError

type UnauthorizedError struct{ Err *Error }

UnauthorizedError indicates the API token is missing or invalid (401).

func (*UnauthorizedError) Error

func (e *UnauthorizedError) Error() string

func (*UnauthorizedError) Unwrap

func (e *UnauthorizedError) Unwrap() error

Unwrap exposes the base *Error to errors.As/Is.

type UpdateContactFieldRequest added in v0.2.0

type UpdateContactFieldRequest struct {
	Name     string `json:"name"`
	MergeTag string `json:"merge_tag"`
}

UpdateContactFieldRequest changes a contact field's name and merge tag; the data type is immutable.

type UpdateContactRequest added in v0.2.0

type UpdateContactRequest struct {
	Email           string         `json:"email"`
	Fields          map[string]any `json:"fields,omitempty"`
	ListIDsIncluded []int64        `json:"list_ids_included,omitempty"`
	ListIDsExcluded []int64        `json:"list_ids_excluded,omitempty"`
	Unsubscribed    *bool          `json:"unsubscribed,omitempty"`
}

UpdateContactRequest is the payload for updating (upserting) a contact. Email is required; ListIDsIncluded and ListIDsExcluded add and remove list memberships.

type UpdateDomainRequest

type UpdateDomainRequest struct {
	OpenTrackingEnabled        *bool `json:"open_tracking_enabled,omitempty"`
	ClickTrackingEnabled       *bool `json:"click_tracking_enabled,omitempty"`
	AutoUnsubscribeLinkEnabled *bool `json:"auto_unsubscribe_link_enabled,omitempty"`
}

UpdateDomainRequest changes a domain's tracking settings. Only the non-nil fields are sent, so leave a field nil to keep its current value.

type UpdateWebhookRequest

type UpdateWebhookRequest struct {
	URL           string   `json:"url,omitempty"`
	Active        *bool    `json:"active,omitempty"`
	PayloadFormat string   `json:"payload_format,omitempty"`
	EventTypes    []string `json:"event_types,omitempty"`
}

UpdateWebhookRequest changes a webhook. Only URL, Active, PayloadFormat, and EventTypes are mutable; only the set fields are sent.

type ValidationError

type ValidationError struct {
	Err    *Error
	Fields map[string][]string
}

ValidationError indicates request validation failed (422). Fields maps each invalid attribute to its messages; the API's record-level errors use "base".

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap exposes the base *Error to errors.As/Is.

type Webhook

type Webhook struct {
	ID     int64  `json:"id"`
	URL    string `json:"url"`
	Active bool   `json:"active"`
	// WebhookType is the kind of webhook.
	WebhookType string `json:"webhook_type"`
	// PayloadFormat is the encoding of delivered payloads.
	PayloadFormat string `json:"payload_format"`
	// SendingStream is the stream the webhook applies to (email_sending only).
	SendingStream  string   `json:"sending_stream,omitempty"`
	DomainID       *int64   `json:"domain_id,omitempty"`
	InboundInboxID *int64   `json:"inbound_inbox_id,omitempty"`
	EventTypes     []string `json:"event_types,omitempty"`
	// SigningSecret verifies payload signatures (HMAC SHA-256). Returned only by
	// Create — store it securely.
	SigningSecret string `json:"signing_secret,omitempty"`
}

Webhook is a subscription that delivers event notifications to a URL.

type WebhooksService

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

WebhooksService manages account webhooks.

func (*WebhooksService) Create

Create adds a webhook. Its SigningSecret is returned only on creation (never by Get or List), so store it to verify payload signatures.

func (*WebhooksService) Delete

func (s *WebhooksService) Delete(ctx context.Context, webhookID int64) (*Webhook, *Response, error)

Delete removes a webhook by ID, returning the deleted webhook.

func (*WebhooksService) Get

func (s *WebhooksService) Get(ctx context.Context, webhookID int64) (*Webhook, *Response, error)

Get returns a webhook by ID. The signing secret is not included; it is only returned by Create.

func (*WebhooksService) List

func (s *WebhooksService) List(ctx context.Context) ([]*Webhook, *Response, error)

List returns all webhooks for the account.

func (*WebhooksService) Update

func (s *WebhooksService) Update(ctx context.Context, webhookID int64, req *UpdateWebhookRequest) (*Webhook, *Response, error)

Update changes a webhook's mutable fields.

Directories

Path Synopsis
examples
accounts command
api-tokens command
attachments command
billing command
contact-events command
contact-exports command
contact-fields command
contact-imports command
contact-lists command
contacts command
email-logs command
email-templates command
messages command
permissions command
projects command
sandbox-sending command
sandboxes command
sending command
sending-domains command
stats command
sub-accounts command
suppressions command
webhooks command
internal
transport
Package transport holds the Mailtrap SDK's HTTP plumbing: token authentication, User-Agent injection, request building, and execution.
Package transport holds the Mailtrap SDK's HTTP plumbing: token authentication, User-Agent injection, request building, and execution.

Jump to

Keyboard shortcuts

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