postmark

package module
v1.6.5 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2024 License: MIT Imports: 8 Imported by: 10

README

Postmark

Fork from Keighl's Postmark (A Golang package for the using Postmark API)

Go Build Status Go Report Card Release GoDoc


Installation
go get -u github.com/mrz1836/postmark

Basic Usage

Grab your Server Token, and your Account Token.

package main

import (
	"context"

	"github.com/mrz1836/postmark"
)

func main() {
	client := postmark.NewClient("[SERVER-TOKEN]", "[ACCOUNT-TOKEN]")

	email := postmark.Email{
		From:       "no-reply@example.com",
		To:         "tito@example.com",
		Subject:    "Reset your password",
		HTMLBody:   "...",
		TextBody:   "...",
		Tag:        "pw-reset",
		TrackOpens: true,
	}

	_, err := client.SendEmail(context.Background(), email)
	if err != nil {
		panic(err)
	}
}

Swap out HTTPClient for use on Google App Engine:

package main

import (
    "github.com/mrz1836/postmark"
    "google.golang.org/appengine"
    "google.golang.org/appengine/urlfetch"
)

// ....

client := postmark.NewClient("[SERVER-TOKEN]", "[ACCOUNT-TOKEN]")

ctx := appengine.NewContext(req)
client.HTTPClient = urlfetch.Client(ctx)

// ...

API Coverage
  • Emails
    • POST /email
    • POST /email/batch
    • POST /email/withTemplate
    • POST /email/batchWithTemplates
  • Bounces
    • GET /deliverystats
    • GET /bounces
    • GET /bounces/:id
    • GET /bounces/:id/dump
    • PUT /bounces/:id/activate
    • GET /bounces/tags
  • Templates
    • GET /templates
    • POST /templates
    • GET /templates/:id
    • PUT /templates/:id
    • DELETE /templates/:id
    • POST /templates/validate
  • Suppressions
    • GET /suppressions/dump
    • POST /suppressions
    • POST /suppressions/delete
  • Servers
    • GET /servers/:id
    • PUT /servers/:id
  • Outbound Messages
    • GET /messages/outbound
    • GET /messages/outbound/:id/details
    • GET /messages/outbound/:id/dump
    • GET /messages/outbound/opens
    • GET /messages/outbound/opens/:id
  • Inbound Messages
    • GET /messages/inbound
    • GET /messages/inbound/:id/details
    • PUT /messages/inbound/:id/bypass
    • PUT /messages/inbound/:id/retry
  • Message Streams
    • GET /message-streams
    • POST /message-streams
    • GET /message-streams/{stream_ID}
    • PATCH /message-streams/{stream_ID}
    • POST /message-streams/{stream_ID}/archive
    • POST /message-streams/{stream_ID}/unarchive
  • Sender signatures
    • GET /senders
    • Get a sender signature’s details
    • Create a signature
    • Edit a signature
    • Delete a signature
    • Resend a confirmation
    • Verify an SPF record
    • Request a new DKIM
  • Stats
    • GET /stats/outbound
    • GET /stats/outbound/sends
    • GET /stats/outbound/bounces
    • GET /stats/outbound/spam
    • GET /stats/outbound/tracked
    • GET /stats/outbound/opens
    • GET /stats/outbound/platform
    • Get email client usage
    • Get email read times
  • Triggers
    • Tags triggers
      • Create a trigger for a tag
      • Get a single trigger
      • Edit a single trigger
      • Delete a single trigger
      • Search triggers
    • Inbound rules triggers
      • Create a trigger for inbound rule
      • Delete a single trigger
      • List triggers
  • Webhooks
    • List webhooks
    • Get webhooks
    • Create webhooks
    • Edit webhooks
    • Delete webhooks
Library Deployment

goreleaser for easy binary or library deployment to GitHub and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                   Runs multiple commands
clean                 Remove previous builds and any test cache data
clean-mods            Remove all the Go mod cache
coverage              Shows the test coverage
diff                  Show the git diff
generate              Runs the go generate command in the base of the repo
godocs                Sync the latest tag with GoDocs
help                  Show this help message
install               Install the application
install-go            Install the application (Using Native Go)
install-releaser      Install the GoReleaser application
lint                  Run the golangci-lint application (install if not found)
release               Full production release (creates release in GitHub)
release               Runs common.release then runs godocs
release-snap          Test the full release (build binaries)
release-test          Full production test release (everything except deploy)
replace-version       Replaces the version in HTML/JS (pre-deploy)
run-examples          Runs all the examples
tag                   Generate a new tag and push (tag version=0.0.0)
tag-remove            Remove a tag if found (tag-remove version=0.0.0)
tag-update            Update an existing tag to current commit (tag-update version=0.0.0)
test                  Runs lint and ALL tests
test-ci               Runs all tests via CI (exports coverage)
test-ci-no-race       Runs all tests via CI (no race) (exports coverage)
test-ci-short         Runs unit tests via CI (exports coverage)
test-no-lint          Runs just tests
test-short            Runs vet, lint and tests (excludes integration tests)
test-unit             Runs tests and outputs coverage
uninstall             Uninstall the application (and remove files)
update-linter         Update the golangci-lint package (macOS only)
vet                   Run the Go vet application

Examples & Tests

All unit tests and examples run via GitHub Actions and uses Go version 1.18.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Run the examples:

make run-examples

License

License

Documentation

Overview

Package postmark encapsulates the Postmark API via Go

Index

Constants

View Source
const (
	// InboundMessageStreamType indicates a message stream is for inbound messages.
	InboundMessageStreamType MessageStreamType = "Inbound"
	// BroadcastMessageStreamType indicates a message stream is for broadcast messages.
	BroadcastMessageStreamType MessageStreamType = "Broadcasts"
	// TransactionalMessageStreamType indicates a message stream is for transactional messages.
	TransactionalMessageStreamType MessageStreamType = "Transactional"

	// NoneUnsubscribeHandlingType indicates a message stream unsubscribe
	// handling will be performed by the user.
	NoneUnsubscribeHandlingType MessageStreamUnsubscribeHandlingType = "None"
	// PostmarkUnsubscribeHandlingType indicates a message stream unsubscribe
	// handling will be performed by postmark.
	PostmarkUnsubscribeHandlingType MessageStreamUnsubscribeHandlingType = "Postmark"
	// CustomUnsubscribeHandlingType indicates a message stream unsubscribe
	// handling is custom.
	CustomUnsubscribeHandlingType MessageStreamUnsubscribeHandlingType = "Custom"
)
View Source
const (
	// HardBounceReason means an email sent to the address returned a hard bounce.
	HardBounceReason SuppressionReasonType = "HardBounce"

	// SpamComplaintReason means the recipient marked an email as spam.
	SpamComplaintReason SuppressionReasonType = "SpamComplaint"

	// ManualSuppressionReason means the recipient followed an unsubscribe link.
	ManualSuppressionReason SuppressionReasonType = "ManualSuppression"

	// RecipientOrigin means the email was added to the suppression list
	// as a result of the recipient's own action, e.g. by following an unsubscribe link.
	RecipientOrigin OriginType = "Recipient"

	// CustomerOrigin means the email was added to the suppression list as
	// the result of action by the Postmark account holder (e.g. Postmark's
	// customer).
	CustomerOrigin OriginType = "Customer"

	// AdminOrigin means the email was added to the suppression list as
	// the result of action by Postmark staff.
	AdminOrigin OriginType = "Admin"

	// SuppressionUpdateStatusSuppressed means the server successfully suppressed the email address.
	SuppressionUpdateStatusSuppressed SuppressionUpdateStatus = "Suppressed"

	// SuppressionUpdateStatusDeleted means the server successfully deleted the suppression.
	SuppressionUpdateStatusDeleted SuppressionUpdateStatus = "Deleted"

	// SuppressionUpdateStatusFailed means the server failed to update the suppression.
	SuppressionUpdateStatusFailed SuppressionUpdateStatus = "Failed"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// ErrorCode: see error codes here (https://postmarkapp.com/developer/api/overview#error-codes)
	ErrorCode int64 `json:"ErrorCode"`
	// Message contains error details
	Message string `json:"Message"`
}

APIError represents errors returned by Postmark

func (APIError) Error

func (res APIError) Error() string

Error returns the error message details

type ArchiveMessageStreamResponse added in v1.6.0

type ArchiveMessageStreamResponse struct {
	// ID of message stream.
	ID string `json:"ID"`
	// Server ID of message stream.
	ServerID int `json:"ServerID"`
	// Expected purge date of message stream. Stream is deleted 45 days after
	// archiving date. Until this date, it can be restored.
	ExpectedPurgeDate string `json:"ExpectedPurgeDate"`
}

ArchiveMessageStreamResponse is the response body for ArchiveMessageStream.

type Attachment

type Attachment struct {
	// Name: attachment name
	Name string
	// Content: Base64 encoded attachment data
	Content string
	// ContentType: attachment MIME type
	ContentType string
	// ContentId: populate for inlining images with the images cid
	ContentID string `json:",omitempty"`
}

Attachment is an optional encoded file to send along with an email

type Bounce

type Bounce struct {
	// ID: ID of bounce
	ID int64
	// Type: Bounce type
	Type string
	// TypeCode: Bounce type code
	TypeCode int64
	// Name: Bounce type name
	Name string
	// Tag: Tag name
	Tag string
	// MessageID: ID of message
	MessageID string
	// Description: Description of bounce
	Description string
	// Details: Details on the bounce
	Details string
	// Email: Email address that bounced
	Email string
	// BouncedAt: Timestamp of bounce
	BouncedAt time.Time
	// DumpAvailable: Specifies whether you can get a raw dump from this bounce. Postmark does not store bounce dumps older than 30 days.
	DumpAvailable bool
	// Inactive: Specifies if the bounce caused Postmark to deactivate this email.
	Inactive bool
	// CanActivate: Specifies whether you are able to reactivate this email.
	CanActivate bool
	// Subject: Email subject
	Subject string
}

Bounce represents a specific delivery failure

type BounceCounts

type BounceCounts struct {
	// Days - List of objects that each represent sent counts by date.
	Days []BounceDay
	// HardBounce - total number of hard bounces
	HardBounce int64
	// SoftBounce - total number of soft bounces
	SoftBounce int64
	// SMTPApiError - total number of SMTP errors
	SMTPApiError int64
	// Transient - total number of transient bounces.
	Transient int64
}

BounceCounts - bounce stats for a period

type BounceDay

type BounceDay struct {
	// Date - self-explanatory
	Date string
	// HardBounce - number of hard bounces
	HardBounce int64
	// SoftBounce - number of soft bounces
	SoftBounce int64
	// SMTPApiError - number of SMTP errors
	SMTPApiError int64
	// Transient - number of transient bounces.
	Transient int64
}

BounceDay - bounce stats for a specific day

type BounceType

type BounceType struct {
	// Type: bounce type identifier
	Type string
	// Name: full name of the bounce type
	Name string
	// Count: how many bounces have occurred
	Count int64
}

BounceType represents a type of bounce, and how many bounces have occurred http://developer.postmarkapp.com/developer-api-bounce.html#bounce-types

type Client

type Client struct {
	// HTTPClient is &http.Client{} by default
	HTTPClient *http.Client
	// Server Token: Used for requests that require server level privileges. This token can be found on the Credentials tab under your Postmark server.
	ServerToken string
	// AccountToken: Used for requests that require account level privileges. This token is only accessible by the account owner, and can be found on the Account tab of your Postmark account.
	AccountToken string
	// BaseURL is the root API endpoint
	BaseURL string
}

Client provides a connection to the Postmark API

func NewClient

func NewClient(serverToken string, accountToken string) *Client

NewClient builds a new Client pointer using the provided tokens, a default HTTPClient, and a default API base URL Accepts `Server Token`, and `Account Token` as arguments http://developer.postmarkapp.com/developer-api-overview.html#authentication

func (*Client) ActivateBounce

func (client *Client) ActivateBounce(ctx context.Context, bounceID int64) (Bounce, string, error)

ActivateBounce reactivates a bounce for resending. Returns the bounce, a message, and any error that occurs TODO: clarify this with Postmark

func (*Client) ArchiveMessageStream added in v1.6.0

func (client *Client) ArchiveMessageStream(ctx context.Context, id string) (ArchiveMessageStreamResponse, error)

ArchiveMessageStream archives a message stream. Archived streams are deleted after 45 days, but they can be restored until that point.

func (*Client) BypassInboundMessage

func (client *Client) BypassInboundMessage(ctx context.Context, messageID string) error

BypassInboundMessage - Bypass rules for a blocked inbound message

func (*Client) CreateMessageStream added in v1.6.0

func (client *Client) CreateMessageStream(ctx context.Context, req CreateMessageStreamRequest) (MessageStream, error)

CreateMessageStream makes a new message stream. It will be created on the server of the token used by this Client.

func (*Client) CreateSuppressions added in v1.6.3

func (client *Client) CreateSuppressions(
	ctx context.Context,
	streamID string,
	suppressions []Suppression,
) ([]SuppressionResponse, error)

CreateSuppressions creates email addresses in the suppression list on the server.

func (*Client) CreateTemplate

func (client *Client) CreateTemplate(ctx context.Context, template Template) (TemplateInfo, error)

CreateTemplate saves a new template to the server

func (*Client) CreateWebhook added in v1.5.0

func (client *Client) CreateWebhook(ctx context.Context, webhook Webhook) (Webhook, error)

CreateWebhook makes a new Webhook. Do not specify the ID in the provided webhook. The returned webhook if successful will include the ID of the created webhook.

func (*Client) DeleteSuppressions added in v1.6.3

func (client *Client) DeleteSuppressions(
	ctx context.Context,
	streamID string,
	suppressions []Suppression,
) ([]SuppressionResponse, error)

DeleteSuppressions deletes email addresses from the suppression list on the server. SpamComplaint suppressions cannot be deleted.

func (*Client) DeleteTemplate

func (client *Client) DeleteTemplate(ctx context.Context, templateID string) error

DeleteTemplate removes a template (with templateID) from the server

func (*Client) DeleteWebhook added in v1.5.0

func (client *Client) DeleteWebhook(ctx context.Context, id int) error

DeleteWebhook removes a webhook from the server.

func (*Client) EditCurrentServer

func (client *Client) EditCurrentServer(ctx context.Context, server Server) (Server, error)

EditCurrentServer updates details for the server associated with the currently in-use server API Key

func (*Client) EditMessageStream added in v1.6.0

func (client *Client) EditMessageStream(ctx context.Context, id string, req EditMessageStreamRequest) (MessageStream, error)

EditMessageStream updates a message stream.

func (*Client) EditServer

func (client *Client) EditServer(ctx context.Context, serverID string, server Server) (Server, error)

EditServer updates details for a specific server with serverID

func (*Client) EditTemplate

func (client *Client) EditTemplate(ctx context.Context, templateID string, template Template) (TemplateInfo, error)

EditTemplate updates details for a specific template with templateID

func (*Client) EditWebhook added in v1.5.0

func (client *Client) EditWebhook(ctx context.Context, id int, webhook Webhook) (Webhook, error)

EditWebhook alters an existing webhook. Do not specify the ID in the provided webhook. The returned webhook if successful will be the resulting state of after the edit.

func (*Client) GetBounce

func (client *Client) GetBounce(ctx context.Context, bounceID int64) (Bounce, error)

GetBounce fetches a single bounce with bounceID

func (*Client) GetBounceCounts

func (client *Client) GetBounceCounts(ctx context.Context, options map[string]interface{}) (BounceCounts, error)

GetBounceCounts - Gets total counts of emails you’ve sent out that have been returned as bounced. Available options: http://developer.postmarkapp.com/developer-api-stats.html#bounce-counts

func (*Client) GetBounceDump

func (client *Client) GetBounceDump(ctx context.Context, bounceID int64) (string, error)

GetBounceDump fetches an SMTP data dump for a single bounce

func (*Client) GetBouncedTags

func (client *Client) GetBouncedTags(ctx context.Context) ([]string, error)

GetBouncedTags retrieves a list of tags that have generated bounced emails

func (*Client) GetBounces

func (client *Client) GetBounces(ctx context.Context, count int64, offset int64, options map[string]interface{}) ([]Bounce, int64, error)

GetBounces returns bounces for the server It returns a Bounce slice, the total bounce count, and any error that occurred Available options: http://developer.postmarkapp.com/developer-api-bounce.html#bounces

func (*Client) GetCurrentServer

func (client *Client) GetCurrentServer(ctx context.Context) (Server, error)

GetCurrentServer gets details for the server associated with the currently in-use server API Key

func (*Client) GetDeliveryStats

func (client *Client) GetDeliveryStats(ctx context.Context) (DeliveryStats, error)

GetDeliveryStats returns delivery stats for the server

func (*Client) GetInboundMessage

func (client *Client) GetInboundMessage(ctx context.Context, messageID string) (InboundMessage, error)

GetInboundMessage fetches a specific inbound message via serverID

func (*Client) GetInboundMessages

func (client *Client) GetInboundMessages(ctx context.Context, count int64, offset int64, options map[string]interface{}) ([]InboundMessage, int64, error)

GetInboundMessages fetches a list of inbound message on the server It returns a InboundMessage slice, the total message count, and any error that occurred http://developer.postmarkapp.com/developer-api-messages.html#inbound-message-search

func (*Client) GetMessageStream added in v1.6.0

func (client *Client) GetMessageStream(ctx context.Context, id string) (MessageStream, error)

GetMessageStream retrieves a specific message stream by the message stream's ID.

func (*Client) GetOpenCounts

func (client *Client) GetOpenCounts(ctx context.Context, options map[string]interface{}) (OpenCounts, error)

GetOpenCounts - Gets total counts of recipients who opened your emails. This is only recorded when open tracking is enabled for that email. Available options: http://developer.postmarkapp.com/developer-api-stats.html#email-opens-count

func (*Client) GetOutboundMessage

func (client *Client) GetOutboundMessage(ctx context.Context, messageID string) (OutboundMessage, error)

GetOutboundMessage fetches a specific outbound message via serverID

func (*Client) GetOutboundMessageDump

func (client *Client) GetOutboundMessageDump(ctx context.Context, messageID string) (string, error)

GetOutboundMessageDump fetches the raw source of message. If no dump is available this will return an empty string.

func (*Client) GetOutboundMessageOpens

func (client *Client) GetOutboundMessageOpens(ctx context.Context, messageID string, count int64, offset int64) ([]Open, int64, error)

GetOutboundMessageOpens fetches a list of opens for a specific message It returns an Open slice, the total opens count, and any error that occurred

func (*Client) GetOutboundMessages

func (client *Client) GetOutboundMessages(ctx context.Context, count int64, offset int64, options map[string]interface{}) ([]OutboundMessage, int64, error)

GetOutboundMessages fetches a list of outbound message on the server It returns a OutboundMessage slice, the total message count, and any error that occurred Note: that a single open is bound to a single recipient, so if the same message was sent to two recipients and both of them opened it, that will be represented by two entries in this array. Available options: http://developer.postmarkapp.com/developer-api-messages.html#outbound-message-search

func (*Client) GetOutboundMessagesOpens

func (client *Client) GetOutboundMessagesOpens(ctx context.Context, count int64, offset int64, options map[string]interface{}) ([]Open, int64, error)

GetOutboundMessagesOpens fetches a list of opens on the server It returns an Open slice, the total opens count, and any error that occurred To get opens for a specific message, use GetOutboundMessageOpens() Available options: http://developer.postmarkapp.com/developer-api-messages.html#message-opens

func (*Client) GetOutboundStats

func (client *Client) GetOutboundStats(ctx context.Context, options map[string]interface{}) (OutboundStats, error)

GetOutboundStats - Gets a brief overview of statistics for all of your outbound email. Available options: http://developer.postmarkapp.com/developer-api-stats.html#overview

func (*Client) GetPlatformCounts

func (client *Client) GetPlatformCounts(ctx context.Context, options map[string]interface{}) (PlatformCounts, error)

GetPlatformCounts gets the email platform usage

func (*Client) GetSenderSignatures

func (client *Client) GetSenderSignatures(ctx context.Context, count, offset int64) (SenderSignaturesList, error)

GetSenderSignatures gets a list of sender signatures, limited by count and paged by offset

func (*Client) GetSentCounts

func (client *Client) GetSentCounts(ctx context.Context, options map[string]interface{}) (SendCounts, error)

GetSentCounts - Gets a total count of emails you’ve sent out. Available options: http://developer.postmarkapp.com/developer-api-stats.html#sent-counts

func (*Client) GetServer

func (client *Client) GetServer(ctx context.Context, serverID string) (Server, error)

GetServer fetches a specific server via serverID

func (*Client) GetSpamCounts

func (client *Client) GetSpamCounts(ctx context.Context, options map[string]interface{}) (SpamCounts, error)

GetSpamCounts - Gets a total count of recipients who have marked your email as spam. Days that did not produce statistics won’t appear in the JSON response. Available options: http://developer.postmarkapp.com/developer-api-stats.html#spam-complaints

func (*Client) GetSuppressions added in v1.4.0

func (client *Client) GetSuppressions(
	ctx context.Context,
	streamID string,
	options map[string]interface{},
) ([]Suppression, error)

GetSuppressions fetches email addresses in the list of suppression dump on the server It returns a Suppressions slice, and any error that occurred https://postmarkapp.com/developer/api/suppressions-api#suppression-dump

func (*Client) GetTemplate

func (client *Client) GetTemplate(ctx context.Context, templateID string) (Template, error)

GetTemplate fetches a specific template via TemplateID

func (*Client) GetTemplates

func (client *Client) GetTemplates(ctx context.Context, count int64, offset int64) ([]TemplateInfo, int64, error)

GetTemplates fetches a list of templates on the server It returns a TemplateInfo slice, the total template count, and any error that occurred Note: TemplateInfo only returns a subset of template attributes, use GetTemplate(id) to retrieve all template info.

func (*Client) GetTrackedCounts

func (client *Client) GetTrackedCounts(ctx context.Context, options map[string]interface{}) (TrackedCounts, error)

GetTrackedCounts - Gets a total count of emails you’ve sent with open tracking enabled. Available options: http://developer.postmarkapp.com/developer-api-stats.html#email-tracked-count

func (*Client) GetWebhook added in v1.5.0

func (client *Client) GetWebhook(ctx context.Context, id int) (Webhook, error)

GetWebhook retrieves a specific webhook by the webhook's ID.

func (*Client) ListMessageStreams added in v1.6.0

func (client *Client) ListMessageStreams(ctx context.Context, messageStreamType string, includeArchived bool) ([]MessageStream, error)

ListMessageStreams returns all message streams for a server. messageStreamType must be one of "All", "Inbound", "Transactional", "Broadcasts" and defaults to "All".

func (*Client) ListWebhooks added in v1.5.0

func (client *Client) ListWebhooks(ctx context.Context, messageStream string) ([]Webhook, error)

ListWebhooks returns all webhooks for a message stream. If the message stream is empty it will return all webhooks for the server. A non-existent message stream will result in an error.

func (*Client) RetryInboundMessage

func (client *Client) RetryInboundMessage(ctx context.Context, messageID string) error

RetryInboundMessage - Retry a failed inbound message for processing

func (*Client) SendEmail

func (client *Client) SendEmail(ctx context.Context, email Email) (EmailResponse, error)

SendEmail sends, well, an email.

func (*Client) SendEmailBatch

func (client *Client) SendEmailBatch(ctx context.Context, emails []Email) ([]EmailResponse, error)

SendEmailBatch sends multiple emails together Note, individual emails in the batch can error, so it would be wise to range over the responses and sniff for errors

func (*Client) SendTemplatedEmail

func (client *Client) SendTemplatedEmail(ctx context.Context, email TemplatedEmail) (EmailResponse, error)

SendTemplatedEmail sends an email using a template (TemplateID)

func (*Client) SendTemplatedEmailBatch

func (client *Client) SendTemplatedEmailBatch(ctx context.Context, emails []TemplatedEmail) ([]EmailResponse, error)

SendTemplatedEmailBatch sends batch email using a template (TemplateID)

func (*Client) UnarchiveMessageStream added in v1.6.0

func (client *Client) UnarchiveMessageStream(ctx context.Context, id string) (MessageStream, error)

UnarchiveMessageStream unarchives a message stream if it has not been deleted yet. The ArchivedAt value will be null after calling this method.

func (*Client) ValidateTemplate

func (client *Client) ValidateTemplate(ctx context.Context, validateTemplateBody ValidateTemplateBody) (ValidateTemplateResponse, error)

ValidateTemplate validates the provided template/render model combination

type CreateMessageStreamRequest added in v1.6.0

type CreateMessageStreamRequest struct {
	// ID of message stream.
	ID string `json:"ID"`
	// Name of message stream.
	Name string `json:"Name"`
	// Description of message stream. This value can be null.
	Description *string `json:"Description,omitempty"`
	// Type of message stream.
	MessageStreamType MessageStreamType `json:"MessageStreamType"`
	// Subscription management options for the Stream
	SubscriptionManagementConfiguration MessageStreamSubscriptionManagementConfiguration `json:"SubscriptionManagementConfiguration"`
}

CreateMessageStreamRequest is the request body for CreateMessageStream. It contains only a subset of the fields of MessageStream.

type DeliveryStats

type DeliveryStats struct {
	// InactiveMails: Number of inactive emails
	InactiveMails int64
	// Bounces: List of bounce types with total counts.
	Bounces []BounceType
}

DeliveryStats represents bounce stats

type EditMessageStreamRequest added in v1.6.0

type EditMessageStreamRequest struct {
	// Name of message stream.
	Name string `json:"Name"`
	// Description of message stream. This value can be null.
	Description *string `json:"Description,omitempty"`
	// Subscription management options for the Stream
	SubscriptionManagementConfiguration MessageStreamSubscriptionManagementConfiguration `json:"SubscriptionManagementConfiguration"`
}

EditMessageStreamRequest is the request body for EditMessageStream. It contains only a subset of the fields of MessageStream.

type Email

type Email struct {
	// From: REQUIRED The sender email address. Must have a registered and confirmed Sender Signature.
	From string `json:",omitempty"`
	// To: REQUIRED Recipient email address. Multiple addresses are comma separated. Max 50.
	To string `json:",omitempty"`
	// Cc recipient email address. Multiple addresses are comma separated. Max 50.
	Cc string `json:",omitempty"`
	// Bcc recipient email address. Multiple addresses are comma separated. Max 50.
	Bcc string `json:",omitempty"`
	// Subject: Email subject
	Subject string `json:",omitempty"`
	// Tag: Email tag that allows you to categorize outgoing emails and get detailed statistics.
	Tag string `json:",omitempty"`
	// HTMLBody: HTML email message. REQUIRED, If no TextBody specified
	HTMLBody string `json:"HtmlBody,omitempty"`
	// TextBody: Plain text email message. REQUIRED, If no HTMLBody specified
	TextBody string `json:",omitempty"`
	// ReplyTo: Reply To override email address. Defaults to the Reply To set in the sender signature.
	ReplyTo string `json:",omitempty"`
	// Headers: List of custom headers to include.
	Headers []Header `json:",omitempty"`
	// TrackOpens: Activate open tracking for this email.
	TrackOpens bool `json:",omitempty"`
	// TrackLinks:Activate link tracking for links in the HTML or Text bodies of this email. Possible options: None HtmlAndText HtmlOnly TextOnly
	TrackLinks string `json:",omitempty"`
	// Attachments: List of attachments
	Attachments []Attachment `json:",omitempty"`
	// Metadata: metadata
	Metadata map[string]string `json:",omitempty"`
	// MessageStream: MessageStream will default to the outbound message stream ID (Default Transactional Stream) if no message stream ID is provided.
	MessageStream string `json:",omitempty"`
}

Email is exactly what it sounds like

type EmailResponse

type EmailResponse struct {
	// To: Recipient email address
	To string
	// SubmittedAt: Timestamp
	SubmittedAt time.Time
	// MessageID: ID of message
	MessageID string
	// ErrorCode: see error codes here (https://postmarkapp.com/developer/api/overview#error-codes)
	ErrorCode int64
	// Message: Response message
	Message string
}

EmailResponse holds info in response to a send/send-batch request Even if API request comes back successful, check the ErrorCode to see if there might be a delivery problem

type Header struct {
	// Name: header name
	Name string `json:",omitempty"`
	// Value: header value
	Value string `json:",omitempty"`
}

Header - an email header

type InboundMessage

type InboundMessage struct {
	// From - The sender email address.
	From string
	// FromName - The sender name.
	FromName string
	// FromFull - Sender email address and name.
	FromFull Recipient
	// To - Inbound address the message was sent to.
	To string
	// ToFull - Slice of all TO recipients
	ToFull []Recipient
	// CcFull - Slice of all CC recipients
	CcFull []Recipient
	// Cc - Cc recipient email address.
	Cc string
	// ReplyTo - Reply to override email address.
	ReplyTo string
	// OriginalRecipient - Receiver (RCPT TO) address this webhook is for.
	OriginalRecipient string
	// Subject - Email subject
	Subject string
	// Date - Timestamp
	Date string
	// MailboxHash - Custom hash that the email was sent to.
	MailboxHash string
	// TextBody - Plain text email message.
	TextBody string
	// HTMLBody - HTML email message.
	HTMLBody string `json:"HtmlBody"`
	// Tag - Tag name
	Tag string
	// Headers - List of objects that each represent a header name and value.
	Headers []Header
	// Attachments - List of objects that each represent an attachment.
	Attachments []Attachment
	// MessageID - Unique ID of the message.
	MessageID string
	// BlockedReason - Reason message was blocked.
	BlockedReason string
	// Status - Status of message in your Postmark activity.
	Status string
}

InboundMessage - a message received from the Postmark server

func (InboundMessage) Time

func (x InboundMessage) Time() (time.Time, error)

Time returns a parsed time.Time struct Inbound messages return as RFC1123Z strangely

type MessageEvent

type MessageEvent struct {
	// Recipient is who received the message (just email address)
	Recipient string
	// ReceivedAt is the event timestamp
	ReceivedAt time.Time
	// Type of event (Delivered, Opened, or Bounced)
	Type string
	// Details contain information regarding the event
	// http://developer.postmarkapp.com/developer-api-messages.html#outbound-message-details
	Details map[string]string
}

MessageEvent represents things that have happened to a message.

type MessageStream added in v1.6.0

type MessageStream struct {
	// ID of message stream.
	ID string `json:"ID"`
	// ID of server the message stream is associated with.
	ServerID int `json:"ServerID"`
	// Name of message stream.
	Name string `json:"Name"`
	// Description of message stream. This value can be null.
	Description *string `json:"Description,omitempty"`
	// Type of message stream.
	MessageStreamType MessageStreamType `json:"MessageStreamType"`
	// Timestamp when message stream was created.
	CreatedAt string `json:"CreatedAt"`
	// Timestamp when message stream was last updated. This value can be null.
	UpdatedAt *string `json:"UpdatedAt,omitempty"`
	// Timestamp when message stream was archived. This value can be null.
	ArchivedAt *string `json:"ArchivedAt,omitempty"`
	// Archived streams are deleted 45 days after archiving date. Until this
	// date, it can be restored. This value is null if the stream is not
	// archived.
	ExpectedPurgeDate *string `json:"ExpectedPurgeDate,omitempty"`
	// Subscription management options for the Stream
	SubscriptionManagementConfiguration MessageStreamSubscriptionManagementConfiguration `json:"SubscriptionManagementConfiguration"`
}

MessageStream holes the configuration for a message stream on a server. https://postmarkapp.com/developer/api/message-streams-api

type MessageStreamSubscriptionManagementConfiguration added in v1.6.0

type MessageStreamSubscriptionManagementConfiguration struct {
	// The unsubscribe management option used for the Stream. Broadcast Message
	// Streams require unsubscribe management, Postmark is default. For Inbound
	// and Transactional Streams default is none.
	UnsubscribeHandlingType MessageStreamUnsubscribeHandlingType `json:"UnsubscribeHandlingType"`
}

MessageStreamSubscriptionManagementConfiguration is the configuration for subscriptions to the message stream.

type MessageStreamType added in v1.6.0

type MessageStreamType string

MessageStreamType is an Enum representing the type of a message stream.

type MessageStreamUnsubscribeHandlingType added in v1.6.0

type MessageStreamUnsubscribeHandlingType string

MessageStreamUnsubscribeHandlingType is an Enum with the possible values for the unsubscribe handling in a message stream.

type Open

type Open struct {
	// FirstOpen - Indicates if the open was first open of message with MessageID and by Recipient. Any subsequent opens of the same message by the same Recipient will show false in this field. Postmark only saves first opens to its store, while all opens are available via Open web hooks.
	FirstOpen bool
	// UserAgent - Full user-agent header passed by the client software to Postmark. Postmark will fill in the Platform Client and OS fields based on this.
	UserAgent string
	// MessageID - Unique ID of the message.
	MessageID string
	// Client - Shows the email client (or browser) used to open the email. Name company and family are described in the parameters specification for this endpoint.
	Client map[string]string
	// OS - Shows the operating system used to open the email.
	OS map[string]string
	// Platform - Shows what platform was used to open the email. WebMail Desktop Mobile Unknown
	Platform string
	// ReadSeconds - Shows the reading time in seconds
	ReadSeconds int64
	// Geo - Contains IP of the recipient’s machine where the email was opened and the information based on that IP - geo coordinates (Coordinates) and country, region, city and zip.
	Geo map[string]string
}

Open represents a single email open.

type OpenCounts

type OpenCounts struct {
	// Days - List of objects that each represent opens by date.
	Days []OpenedDay
	// Opens - Indicates total number of opened emails. This total includes recipients who opened your email multiple times.
	Opens int64
	// Unique int64 - Indicates total number of uniquely opened emails.
	Unique int64
}

OpenCounts - opened outbound emails for a period

type OpenedDay

type OpenedDay struct {
	// Date - self-explanatory
	Date string
	// Opens - Indicates total number of opened emails. This total includes recipients who opened your email multiple times.
	Opens int64
	// Unique - Indicates total number of uniquely opened emails.
	Unique int64
}

OpenedDay - opened outbound emails sent on a specific day

type OriginType added in v1.4.0

type OriginType string

OriginType - The reason type of origin

type OutboundMessage

type OutboundMessage struct {
	// TextBody - Text body of the message.
	TextBody string
	// HTMLBody - Html body of the message.
	HTMLBody string `json:"HtmlBody"`
	// Body - Raw source of the message.
	Body string
	// Tag - Tags associated with this message.
	Tag string
	// MessageID - Unique ID of the message.
	MessageID string
	// To - List of objects that contain To recipients.
	To []Recipient
	// Cc - List of objects that contain Cc recipients.
	Cc []Recipient
	// Bcc - List of objects that contain Bcc recipients.
	Bcc []Recipient
	// Recipients - List of recipients (just emails)
	Recipients []string
	// ReceivedAt - Timestamp
	ReceivedAt time.Time
	// From - The sender email address.
	From string
	// Subject - Email subject
	Subject string
	// Attachments - List of objects that each represent an attachment.
	Attachments []string
	// Status - Status of message in your Postmark activity.
	Status string
	// MessageEvents - List of summaries (MessageEvent) of things that have happened to this message. They can be Delivered, Opened, or Bounced as shown in the type field.
	MessageEvents []MessageEvent
}

OutboundMessage - a message sent from the Postmark server

type OutboundStats

type OutboundStats struct {
	// Sent - Number of sent emails
	Sent int64
	// Bounced - Number of bounced emails
	Bounced int64
	// SMTPApiErrors - Number of SMTP errors
	SMTPApiErrors int64
	// BounceRate - Bounce rate percentage calculated by total sent.
	BounceRate float64
	// SpamComplaints - Number of spam complaints received
	SpamComplaints int64
	// SpamComplaintsRate - Spam complaints percentage calculated by total sent.
	SpamComplaintsRate float64
	// Opens - Number of opens
	Opens int64
	// UniqueOpens - Number of unique opens
	UniqueOpens int64
	// Tracked - Number of tracked emails sent
	Tracked int64
	// WithClientRecorded - Number of emails where the client was successfully tracked.
	WithClientRecorded int64
	// WithPlatformRecorded - Number of emails where platform was successfully tracked.
	WithPlatformRecorded int64
	// WithReadTimeRecorded - Number of emails where read time was successfully tracked.
	WithReadTimeRecorded int64
}

OutboundStats - a brief overview of statistics for all of your outbound email.

type PlatformCounts

type PlatformCounts struct {
	// Days - List of objects that each represent email platform usages by date
	Days []PlatformDay
	// Desktop - The total number of email platform usages by Desktop
	Desktop int64

	// Mobile - The total number of email platform usages by Mobile
	Mobile int64

	// Unknown - The total number of email platform usages by others
	Unknown int64

	// WebMail - The total number of email platform usages by WebMail
	WebMail int64
}

PlatformCounts contains day-to-day usages, along with totals of email usages by platform

type PlatformDay

type PlatformDay struct {
	// Date - the date in question
	Date string

	// Desktop - The total number of email platform usages by Desktop for this date
	Desktop int64

	// Mobile - The total number of email platform usages by Mobile for this date
	Mobile int64

	// Unknown - The total number of email platform usages by others for this date
	Unknown int64

	// WebMail - The total number of email platform usages by WebMail for this date
	WebMail int64
}

PlatformDay contains the totals of email usages by platform for a specific date

type Recipient

type Recipient struct {
	// Name is the recipient's name
	Name string
	// Emails is the recipient's email address
	Email string
}

Recipient represents an individual who received a message

type SendCounts

type SendCounts struct {
	// Days - List of objects that each represent sent counts by date.
	Days []SendDay
	// Sent - Indicates the number of total sent emails returned.
	Sent int64
}

SendCounts - send stats for a period

type SendDay

type SendDay struct {
	// Date - self-explanatory
	Date string
	// Sent - number of emails sent
	Sent int64
}

SendDay - send stats for a specific day

type SenderSignature

type SenderSignature struct {
	Domain              string
	EmailAddress        string
	ReplyToEmailAddress string
	Name                string
	Confirmed           bool
	ID                  int64
}

SenderSignature contains the details of the signature of the senders

type SenderSignaturesList

type SenderSignaturesList struct {
	TotalCount       int
	SenderSignatures []SenderSignature
}

SenderSignaturesList is just a list of SenderSignatures as they are in the response

type Server

type Server struct {
	// ID of server
	ID int64
	// Name of server
	Name string
	// APITokens associated with server.
	APITokens []string `json:"ApiTokens"`
	// ServerLink to your server overview page in Postmark.
	ServerLink string
	// Color of the server in the rack screen. Purple Blue Turquoise Green Red Yellow Grey
	Color string
	// SMTPAPIActivated specifies whether SMTP is enabled on this server.
	SMTPAPIActivated bool `json:"SmtpApiActivated"`
	// RawEmailEnabled allows raw email to be sent with inbound.
	RawEmailEnabled bool
	// InboundAddress is the inbound email address
	InboundAddress string
	// InboundHookURL to POST to every time an inbound event occurs.
	InboundHookURL string `json:"InboundHookUrl"`
	// BounceHookURL to POST to every time a bounce event occurs.
	BounceHookURL string `json:"BounceHookUrl"`
	// OpenHookURL to POST to every time an open event occurs.
	OpenHookURL string `json:"OpenHookUrl"`
	// PostFirstOpenOnly - If set to true, only the first open by a particular recipient will initiate the open webhook. Any
	// subsequent opens of the same email by the same recipient will not initiate the webhook.
	PostFirstOpenOnly bool
	// TrackOpens indicates if all emails being sent through this server have open tracking enabled.
	TrackOpens bool
	// InboundDomain is the inbound domain for MX setup
	InboundDomain string
	// InboundHash is the inbound hash of your inbound email address.
	InboundHash string
	// InboundSpamThreshold is the maximum spam score for an inbound message before it's blocked.
	InboundSpamThreshold int64
}

Server represents a server registered in your Postmark account

type SpamCounts

type SpamCounts struct {
	// Days - List of objects that each represent spam complaint counts by date.
	Days []SpamDay
	// SpamComplaint - Indicates total number of spam complaints.
	SpamComplaint int64
}

SpamCounts - spam complaints for a period

type SpamDay

type SpamDay struct {
	// Date - self-explanatory
	Date string
	// SpamComplaint - number of spam complaints received
	SpamComplaint int64
}

SpamDay - spam complaints for a specific day

type Suppression added in v1.4.0

type Suppression struct {
	// EmailAddress is the address that is suppressed (can't be emailed any more)
	EmailAddress string

	// SuppressionReason is why the email address was added to the suppression list.
	// Possible options: HardBounce, SpamComplaint, ManualSuppression
	SuppressionReason SuppressionReasonType

	// Origin describes who added the email address to the suppression list.
	// Possible options: Recipient, Customer, Admin.
	Origin OriginType

	// CreatedAt is when the email address was added to the suppression list.
	CreatedAt time.Time
}

Suppression contains a suppressed email address for a particular message stream.

type SuppressionReasonType added in v1.4.0

type SuppressionReasonType string

SuppressionReasonType - The reason type of suppression

type SuppressionResponse added in v1.6.3

type SuppressionResponse struct {
	// EmailAddress is the address that is suppressed (can't be emailed any more)
	EmailAddress string

	// Status of suppression creation or deletion.
	Status SuppressionUpdateStatus

	// If address cannot be suppressed or deleted (Status: Failed), the cause for failure is listed.
	// Otherwise, this field is null.
	Message string
}

SuppressionResponse contains a status of suppression creation or deletion.

type SuppressionUpdateStatus added in v1.6.3

type SuppressionUpdateStatus string

SuppressionUpdateStatus - The status of suppression update

type Template

type Template struct {
	// TemplateID: ID of template
	TemplateID int64 `json:"TemplateID"`
	// Name: Name of template
	Name string
	// Subject: The content to use for the Subject when this template is used to send email.
	Subject string
	// HTMLBody: The content to use for the HTMLBody when this template is used to send email.
	HTMLBody string `json:"HtmlBody"`
	// TextBody: The content to use for the TextBody when this template is used to send email.
	TextBody string
	// AssociatedServerID: The ID of the Server with which this template is associated.
	AssociatedServerID int64 `json:"AssociatedServerId"`
	// Active: Indicates that this template may be used for sending email.
	Active bool
}

Template represents an email template on the server

type TemplateInfo

type TemplateInfo struct {
	// TemplateID: ID of template
	TemplateID int64 `json:"TemplateID"`
	// Name: Name of template
	Name string
	// Active: Indicates that this template may be used for sending email.
	Active bool
}

TemplateInfo is a limited set of template info returned via Index/Editing endpoints

type TemplatedEmail

type TemplatedEmail struct {
	// TemplateID: REQUIRED if TemplateAlias is not specified. - The template id to use when sending this message.
	TemplateID int64 `json:"TemplateId,omitempty"`
	// TemplateAlias: REQUIRED if TemplateID is not specified. - The template alias to use when sending this message.
	TemplateAlias string `json:",omitempty"`
	// TemplateModel: The model to be applied to the specified template to generate HtmlBody, TextBody, and Subject.
	TemplateModel map[string]interface{} `json:",omitempty"`
	// InlineCSS: By default, if the specified template contains an HtmlBody, we will apply the style blocks as inline attributes to the rendered HTML content. You may opt out of this behavior by passing false for this request field.
	InlineCSS bool `json:"InlineCSS,omitempty"`
	// From: The sender email address. Must have a registered and confirmed Sender Signature.
	From string `json:",omitempty"`
	// To: REQUIRED Recipient email address. Multiple addresses are comma separated. Max 50.
	To string `json:",omitempty"`
	// Cc recipient email address. Multiple addresses are comma separated. Max 50.
	Cc string `json:",omitempty"`
	// Bcc recipient email address. Multiple addresses are comma separated. Max 50.
	Bcc string `json:",omitempty"`
	// Tag: Email tag that allows you to categorize outgoing emails and get detailed statistics.
	Tag string `json:",omitempty"`
	// Reply To override email address. Defaults to the Reply To set in the sender signature.
	ReplyTo string `json:",omitempty"`
	// Headers: List of custom headers to include.
	Headers []Header `json:",omitempty"`
	// TrackOpens: Activate open tracking for this email.
	TrackOpens bool `json:",omitempty"`
	// TrackLinks: Activate link tracking. Possible options: "None", "HtmlAndText", "HtmlOnly", "TextOnly".
	TrackLinks string `json:",omitempty"`
	// Attachments: List of attachments
	Attachments []Attachment `json:",omitempty"`
	// MessageStream: MessageStream will default to the outbound message stream ID (Default Transactional Stream) if no message stream ID is provided.
	MessageStream string `json:",omitempty"`
	// Metadata: Custom metadata key/value pairs.
	Metadata map[string]interface{} `json:",omitempty"`
}

TemplatedEmail is used to send an email via a template

type TrackedCounts

type TrackedCounts struct {
	// Days - List of objects that each represent tracked email counts by date.
	Days []TrackedDay
	// Tracked - Indicates total number of tracked emails sent.
	Tracked int64
}

TrackedCounts - tracked emails sent for a period

type TrackedDay

type TrackedDay struct {
	// Date - self-explanatory
	Date string
	// Tracked - number of emails tracked sent
	Tracked int64
}

TrackedDay - tracked emails sent on a specific day

type ValidateTemplateBody

type ValidateTemplateBody struct {
	Subject                    string
	TextBody                   string
	HTMLBody                   string `json:"HTMLBody"`
	TestRenderModel            map[string]interface{}
	InlineCSSForHTMLTestRender bool `json:"InlineCssForHtmlTestRender"`
}

ValidateTemplateBody contains the template/render model combination to be validated

type ValidateTemplateResponse

type ValidateTemplateResponse struct {
	AllContentIsValid      bool
	HTMLBody               Validation `json:"HTMLBody"`
	TextBody               Validation
	Subject                Validation
	SuggestedTemplateModel map[string]interface{}
}

ValidateTemplateResponse contains information as to how the validation went

type Validation

type Validation struct {
	ContentIsValid   bool
	ValidationErrors []ValidationError
	RenderedContent  string
}

Validation contains the results of a field's validation

type ValidationError

type ValidationError struct {
	Message           string
	Line              int
	CharacterPosition int
}

ValidationError contains information about the errors which occurred during validation for a given field

type Webhook added in v1.5.0

type Webhook struct {
	// ID of webhook.
	ID int `json:"ID,omitempty"`
	// Your webhook URL.
	URL string `json:"Url"`
	// The stream this webhook is associated with.
	MessageStream string `json:"MessageStream"`
	// Optional. HTTP Auth username and password.
	HTTPAuth *WebhookHTTPAuth `json:"HttpAuth,omitempty"`
	// Optional. List of custom headers included.
	HTTPHeaders []Header `json:"HttpHeaders,omitempty"`
	// List of different possible triggers a webhook can be enabled/disabled for.
	Triggers WebhookTrigger `json:"Triggers"`
}

Webhook is a configured webhook on a message stream. https://postmarkapp.com/developer/api/webhooks-api#get-a-webhook

type WebhookHTTPAuth added in v1.5.0

type WebhookHTTPAuth struct {
	// HTTP Auth username.
	Username string `json:"Username"`
	// HTTP Auth password.
	Password string `json:"Password"`
}

WebhookHTTPAuth is an optional set of auth configuration to use when calling the webhook.

type WebhookTrigger added in v1.5.0

type WebhookTrigger struct {
	// List of open webhook details.
	Open WebhookTriggerOpen `json:"Open"`
	// List of click webhook details.
	Click WebhookTriggerEnabled `json:"Click"`
	// List of delivery webhook details.
	Delivery WebhookTriggerEnabled `json:"Delivery"`
	// List of bounce webhook details.
	Bounce WebhookTriggerIncContent `json:"Bounce"`
	// List of spam complaint webhook details.
	SpamComplaint WebhookTriggerIncContent `json:"SpamComplaint"`
	// List of subscription change webhook details.
	SubscriptionChange WebhookTriggerEnabled `json:"SubscriptionChange"`
}

WebhookTrigger holds configuration for when this webhook should be called.

type WebhookTriggerEnabled added in v1.5.0

type WebhookTriggerEnabled struct {
	// Specifies whether this webhook is enabled.
	Enabled bool `json:"Enabled"`
}

WebhookTriggerEnabled holds configuration for webhooks which can only be enabled or disabled.

type WebhookTriggerIncContent added in v1.5.0

type WebhookTriggerIncContent struct {
	WebhookTriggerEnabled
	// Specifies whether the full content of the email is included in webhook POST.
	IncludeContent bool `json:"IncludeContent"`
}

WebhookTriggerIncContent holds configuration for webhooks which can be enabled/disabled and optionally include message contents.

type WebhookTriggerOpen added in v1.5.0

type WebhookTriggerOpen struct {
	WebhookTriggerEnabled
	PostFirstOpenOnly bool `json:"PostFirstOpenOnly"`
}

WebhookTriggerOpen holds configuration for the Open webhook.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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