gosparkpost

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2020 License: Apache-2.0 Imports: 16 Imported by: 27

README

.. image:: https://www.sparkpost.com/sites/default/files/attachments/SparkPost_Logo_2-Color_Gray-Orange_RGB.svg
    :target: https://www.sparkpost.com
    :width: 200px

`Sign up`_ for a SparkPost account and visit our `Developer Hub`_ for even more content.

.. _Sign up: https://app.sparkpost.com/join?plan=free-0817?src=Social%20Media&sfdcid=70160000000pqBb&pc=GitHubSignUp&utm_source=github&utm_medium=social-media&utm_campaign=github&utm_content=sign-up
.. _Developer Hub: https://developers.sparkpost.com

SparkPost Go API client
=======================

.. image:: https://travis-ci.org/SparkPost/gosparkpost.svg?branch=master
    :target: https://travis-ci.org/SparkPost/gosparkpost
    :alt: Build Status

.. image:: https://coveralls.io/repos/SparkPost/gosparkpost/badge.svg?branch=master&service=github
    :target: https://coveralls.io/github/SparkPost/gosparkpost?branch=master
    :alt: Code Coverage  
    
.. image:: https://img.shields.io/badge/godoc-gosparkpost-blue.svg
    :target: https://godoc.org/github.com/SparkPost/gosparkpost
    :alt: Go Doc


The official Go package for using the SparkPost API.

Installation
------------

Install from GitHub using `go get`_:

.. code-block:: bash

    $ go get github.com/SparkPost/gosparkpost

.. _go get: https://golang.org/cmd/go/#hdr-Download_and_install_packages_and_dependencies

Get a key
---------

Go to `API & SMTP`_ in the SparkPost app and create an API key. We recommend using the ``SPARKPOST_API_KEY`` environment variable. The example code below shows how to set this up.

.. _API & SMTP: https://app.sparkpost.com/#/configuration/credentials

Send a message
--------------

Here at SparkPost, our "send some messages" api is called the `transmissions API`_ - let's use it to send a friendly test message:

.. code-block:: go

    package main

    import (
      "log"
      "os"

      sp "github.com/SparkPost/gosparkpost"
    )

    func main() {
      // Get our API key from the environment; configure.
      apiKey := os.Getenv("SPARKPOST_API_KEY")
      cfg := &sp.Config{
        BaseUrl:    "https://api.sparkpost.com",
        ApiKey:     apiKey,
        ApiVersion: 1,
      }
      var client sp.Client
      err := client.Init(cfg)
      if err != nil {
        log.Fatalf("SparkPost client init failed: %s\n", err)
      }

      // Create a Transmission using an inline Recipient List
      // and inline email Content.
      tx := &sp.Transmission{
        Recipients: []string{"someone@somedomain.com"},
        Content: sp.Content{
          HTML:    "<p>Hello world</p>",
          From:    "test@sparkpostbox.com",
          Subject: "Hello from gosparkpost",
        },
      }
      id, _, err := client.Send(tx)
      if err != nil {
        log.Fatal(err)
      }

      // The second value returned from Send
      // has more info about the HTTP response, in case
      // you'd like to see more than the Transmission id.
      log.Printf("Transmission sent with id [%s]\n", id)
    }

.. _transmissions API: https://www.sparkpost.com/api#/reference/transmissions

Documentation
-------------

* `SparkPost API Reference`_
* `Code samples`_
* `Command-line tool: sparks`_

.. _SparkPost API Reference: https://developers.sparkpost.com/api
.. _Code samples: examples/README.md
.. _Command-line tool\: sparks: cmd/sparks/README.md

Contribute
----------

TL;DR:

#. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug.
#. Fork `the repository`_.
#. Go get the original code - ``go get https://github.com/SparkPost/gosparkpost``
#. Add your fork as a remote - ``git remote add fork http://github.com/YOURID/gosparkpost``
#. Make your changes in a branch on your fork
#. Write a test which shows that the bug was fixed or that the feature works as expected.
#. Push your changes - ``git push fork HEAD``
#. Send a pull request. Make sure to add yourself to AUTHORS_.

More on the `contribution process`_

.. _`the repository`: https://github.com/SparkPost/gosparkpost
.. _AUTHORS: AUTHORS.rst
.. _`contribution process`: CONTRIBUTING.md

Documentation

Index

Examples

Constants

View Source
const (
	StaticToken = iota
	MacroToken
)

Variables

View Source
var (
	MessageEventsPathFormat        = "/api/v%d/message-events"
	MessageEventsSamplesPathFormat = "/api/v%d/message-events/events/samples"
)

https://www.sparkpost.com/api#/reference/message-events

View Source
var EventDocumentationFormat = "/api/v%d/webhooks/events/documentation"
View Source
var MetricsPathFormat = "/api/v%d/metrics/deliverability"
View Source
var RecipientListsPathFormat = "/api/v%d/recipient-lists"

https://www.sparkpost.com/api#/reference/recipient-lists

View Source
var SubaccountGrants = []string{
	"smtp/inject",
	"sending_domains/manage",
	"message_events/view",
	"suppression_lists/manage",
	"tracking_domains/view",
	"tracking_domains/manage",
	"transmissions/view",
	"transmissions/modify",
}

SubaccountGrants contains the grants that will be given to new subaccounts by default.

View Source
var SubaccountStatuses = []string{
	"active",
	"suspended",
	"terminated",
}

SubaccountStatuses contains valid subaccount statuses.

View Source
var SubaccountsPathFormat = "/api/v%d/subaccounts"

SubaccountsPathFormat provides an easy way to fill out the path including the version.

View Source
var SuppressionListsPathFormat = "/api/v%d/suppression-list"

SuppressionListsPathFormat https://developers.sparkpost.com/api/#/reference/suppression-list

View Source
var TemplatesPathFormat = "/api/v%d/templates"

https://www.sparkpost.com/api#/reference/templates

View Source
var TransmissionsPathFormat = "/api/v%d/transmissions"

TransmissionsPathFormat https://www.sparkpost.com/api#/reference/transmissions

View Source
var WebhooksPathFormat = "/api/v%d/webhooks"

WebhooksPathFormat is the path prefix used for webhook-related requests, with a format string for the API version.

Functions

func Is2XX

func Is2XX(code int) bool

Is2XX returns true if the provided HTTP response code is in the range 200-299.

func ParseContent

func ParseContent(content interface{}) (err error)

ParseContent asserts that Transmission.Content is valid.

func ParseRecipients

func ParseRecipients(recips interface{}) (ra *[]Recipient, err error)

ParseRecipients asserts that Transmission.Recipients is valid.

Types

type Address

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

Address describes the nested object way of specifying the Recipient's email address. Recipient.Address can also be a plain string.

func ParseAddress

func ParseAddress(addr interface{}) (a Address, err error)

ParseAddress parses the various allowable Content.From values.

type Attachment

type Attachment struct {
	MIMEType string `json:"type"`
	Filename string `json:"name"`
	B64Data  string `json:"data"`
}

Attachment contains metadata and the contents of the file to attach.

type Client

type Client struct {
	Config  *Config
	Client  *http.Client
	Headers *http.Header
	// contains filtered or unexported fields
}

Client contains connection, configuration, and authentication information. Specifying your own http.Client gives you lots of control over how connections are made. Clients are safe for concurrent (read-only) reuse by multiple goroutines. Headers is useful to set subaccount (X-MSYS-SUBACCOUNT header) and any other custom headers. All changes to Headers must happen before Client is exposed to possible concurrent use.

func (*Client) ApplyMacros added in v0.2.0

func (c *Client) ApplyMacros(in string, r *Recipient) (string, error)

ApplyMacros runs all Macros registered with the Client against the provided string, returning the result. If a Recipient is provided, substitution is performed on the macro parameter before the macro runs. Any placeholders not handled by a macro are left intact.

func (*Client) DoRequest

func (c *Client) DoRequest(ctx context.Context, method, urlStr string, data []byte) (*Response, error)

func (*Client) EventDocumentation

func (c *Client) EventDocumentation() (g map[string]*EventGroup, res *Response, err error)

func (*Client) EventDocumentationContext

func (c *Client) EventDocumentationContext(ctx context.Context) (groups map[string]*EventGroup, res *Response, err error)

func (*Client) EventSamples

func (c *Client) EventSamples(types []string) (*events.Events, *Response, error)

EventSamples requests a list of example event data.

func (*Client) EventSamplesContext

func (c *Client) EventSamplesContext(ctx context.Context, types []string) (*events.Events, *Response, error)

EventSamplesContext is the same as EventSamples, and it accepts a context.Context

func (*Client) HttpDelete

func (c *Client) HttpDelete(ctx context.Context, url string) (*Response, error)

HttpDelete sends a Delete request to the provided url. Query params are supported via net/url - roll your own and stringify it. Authenticate using the configured API key.

func (*Client) HttpGet

func (c *Client) HttpGet(ctx context.Context, url string) (*Response, error)

HttpGet sends a Get request to the specified url. Query params are supported via net/url - roll your own and stringify it. Authenticate using the configured API key.

func (*Client) HttpGetJson added in v0.2.0

func (c *Client) HttpGetJson(ctx context.Context, url string, ptr interface{}) (*Response, error)

HttpGetJson sends a GET request to the specified url and returns the JSON result. An error is returned if the response's Content-Type isn't JSON. The JSON reponse is Unmarshalled into the provided interface{} value.

func (*Client) HttpPost

func (c *Client) HttpPost(ctx context.Context, url string, data []byte) (*Response, error)

HttpPost sends a Post request with the provided JSON payload to the specified url. Query params are supported via net/url - roll your own and stringify it. Authenticate using the configured API key.

func (*Client) HttpPut

func (c *Client) HttpPut(ctx context.Context, url string, data []byte) (*Response, error)

HttpPut sends a Put request with the provided JSON payload to the specified url. Query params are supported via net/url - roll your own and stringify it. Authenticate using the configured API key.

func (*Client) HttpPutJson added in v0.2.0

func (c *Client) HttpPutJson(ctx context.Context, url string, data []byte) (*Response, error)

HttpPutJson sends a PUT request to the specified url and returns the JSON result. An error is returned if the response's Content-Type isn't JSON.

func (*Client) Init

func (c *Client) Init(cfg *Config) error

Init pulls together everything necessary to make an API request. Caller may provide their own http.Client by setting it in the provided API object.

func (*Client) MessageEventsSearchContext

func (c *Client) MessageEventsSearchContext(ctx context.Context, page *EventsPage) (*Response, error)

MessageEventsSearchContext is the same as MessageEventsSearch, and it accepts a context.Context

func (*Client) QueryMetricsContext

func (c *Client) QueryMetricsContext(ctx context.Context, m *Metrics) (*Response, error)

func (*Client) RecipientListCreate

func (c *Client) RecipientListCreate(rl *RecipientList) (id string, res *Response, err error)

RecipientListCreate accepts a populated RecipientList object, validates it, and performs an API call against the configured endpoint.

func (*Client) RecipientListCreateContext

func (c *Client) RecipientListCreateContext(ctx context.Context, rl *RecipientList) (id string, res *Response, err error)

RecipientListCreateContext is the same as RecipientListCreate, and it accepts a context.Context

func (*Client) RecipientLists

func (c *Client) RecipientLists() ([]RecipientList, *Response, error)

RecipientLists returns all recipient lists

func (*Client) RecipientListsContext

func (c *Client) RecipientListsContext(ctx context.Context) ([]RecipientList, *Response, error)

RecipientListsContext is the same as RecipientLists, and it accepts a context.Context

func (*Client) RegisterMacro added in v0.2.0

func (c *Client) RegisterMacro(m *Macro) error

RegisterMacro associates a Macro with a Client. As with all changes to the Client, this is only safe to call before any potential concurrency. Everything between the Macro Name and the closing delimiter will be passed to the Func as a single string argument.

func (*Client) Send

func (c *Client) Send(t *Transmission) (id string, res *Response, err error)

Send accepts a populated Transmission object, performs basic sanity checks on it, and performs an API call against the configured endpoint. Calling this function can cause email to be sent, if used correctly.

func (*Client) SendContext

func (c *Client) SendContext(ctx context.Context, t *Transmission) (id string, res *Response, err error)

SendContext does the same thing as Send, and in addition it accepts a context from the caller.

func (*Client) Subaccount

func (c *Client) Subaccount(id int) (subaccount *Subaccount, res *Response, err error)

Subaccount looks up a subaccount using the provided id

func (*Client) SubaccountContext

func (c *Client) SubaccountContext(ctx context.Context, id int) (subaccount *Subaccount, res *Response, err error)

SubaccountContext is the same as Subaccount, and it accepts a context.Context

func (*Client) SubaccountCreate

func (c *Client) SubaccountCreate(s *Subaccount) (res *Response, err error)

SubaccountCreate attempts to create a subaccount using the provided object

func (*Client) SubaccountCreateContext

func (c *Client) SubaccountCreateContext(ctx context.Context, s *Subaccount) (res *Response, err error)

SubaccountCreateContext is the same as SubaccountCreate, and it allows the caller to pass in a context New subaccounts will have all grants in SubaccountGrants, unless s.Grants is non-nil.

func (*Client) SubaccountUpdate

func (c *Client) SubaccountUpdate(s *Subaccount) (res *Response, err error)

SubaccountUpdate updates a subaccount with the specified id. It marshals and sends all the subaccount fields, ignoring the read-only ones.

func (*Client) SubaccountUpdateContext

func (c *Client) SubaccountUpdateContext(ctx context.Context, s *Subaccount) (res *Response, err error)

SubaccountUpdateContext is the same as SubaccountUpdate, and it allows the caller to provide a context

func (*Client) Subaccounts

func (c *Client) Subaccounts() (subaccounts []Subaccount, res *Response, err error)

Subaccounts returns metadata for all Subaccounts in the system.

func (*Client) SubaccountsContext

func (c *Client) SubaccountsContext(ctx context.Context) (subaccounts []Subaccount, res *Response, err error)

SubaccountsContext is the same as Subaccounts, and it allows the caller to provide a context

func (*Client) SuppressionDelete

func (c *Client) SuppressionDelete(email string) (res *Response, err error)

SuppressionDelete deletes an entry from the suppression list

func (*Client) SuppressionDeleteContext

func (c *Client) SuppressionDeleteContext(ctx context.Context, email string) (res *Response, err error)

SuppressionDeleteContext deletes an entry from the suppression list

func (*Client) SuppressionList

func (c *Client) SuppressionList(sp *SuppressionPage) (*Response, error)

SuppressionList retrieves the account's suppression list. Suppression lists larger than 10,000 entries will need to use cursor to retrieve more results. See https://developers.sparkpost.com/api/suppression-list.html#suppression-list-search-get

func (*Client) SuppressionListContext

func (c *Client) SuppressionListContext(ctx context.Context, sp *SuppressionPage) (*Response, error)

SuppressionListContext retrieves the account's suppression list

func (*Client) SuppressionRetrieve

func (c *Client) SuppressionRetrieve(email string, sp *SuppressionPage) (*Response, error)

SuppressionRetrieve retrieves the suppression status for a specific recipient by specifying the recipient’s email address // https://developers.sparkpost.com/api/suppression-list.html#suppression-list-retrieve,-delete,-insert-or-update-get

func (*Client) SuppressionRetrieveContext

func (c *Client) SuppressionRetrieveContext(ctx context.Context, email string, sp *SuppressionPage) (*Response, error)

SuppressionRetrieveContext retrieves the suppression status for a specific recipient by specifying the recipient’s email address // https://developers.sparkpost.com/api/suppression-list.html#suppression-list-retrieve,-delete,-insert-or-update-get

func (*Client) SuppressionSearch

func (c *Client) SuppressionSearch(sp *SuppressionPage) (*Response, error)

SuppressionSearch search for suppression entries. For a list of parameters see https://developers.sparkpost.com/api/suppression-list.html#suppression-list-search-get

func (*Client) SuppressionSearchContext

func (c *Client) SuppressionSearchContext(ctx context.Context, sp *SuppressionPage) (*Response, error)

SuppressionSearchContext search for suppression entries. For a list of parameters see https://developers.sparkpost.com/api/suppression-list.html#suppression-list-search-get

func (*Client) SuppressionUpsert

func (c *Client) SuppressionUpsert(entries []WritableSuppressionEntry) (*Response, error)

SuppressionUpsert adds an entry to the suppression, or updates the existing entry

func (*Client) SuppressionUpsertContext

func (c *Client) SuppressionUpsertContext(ctx context.Context, entries []WritableSuppressionEntry) (*Response, error)

SuppressionUpsertContext is the same as SuppressionUpsert, and it accepts a context.Context

func (*Client) TemplateCreate

func (c *Client) TemplateCreate(t *Template) (id string, res *Response, err error)

TemplateCreate accepts a populated Template object, validates its Contents, and performs an API call against the configured endpoint.

func (*Client) TemplateCreateContext

func (c *Client) TemplateCreateContext(ctx context.Context, t *Template) (id string, res *Response, err error)

TemplateCreateContext is the same as TemplateCreate, and it allows the caller to provide a context.

func (*Client) TemplateDelete

func (c *Client) TemplateDelete(id string) (res *Response, err error)

TemplateDelete removes the Template with the specified id.

func (*Client) TemplateDeleteContext

func (c *Client) TemplateDeleteContext(ctx context.Context, id string) (res *Response, err error)

TemplateDeleteContext is the same as TemplateDelete, and it allows the caller to provide a context

func (*Client) TemplateGet

func (c *Client) TemplateGet(t *Template, draft bool) (*Response, error)

TemplateGet fills out the provided template, using the specified id.

func (*Client) TemplateGetContext

func (c *Client) TemplateGetContext(ctx context.Context, t *Template, draft bool) (*Response, error)

TemplateGetContext is the same as TemplateGet, and it allows the caller to provide a context

func (*Client) TemplatePreview

func (c *Client) TemplatePreview(id string, payload *PreviewOptions) (res *Response, err error)

TemplatePreview renders and returns the output of a template using the provided substitution data.

func (*Client) TemplatePreviewContext

func (c *Client) TemplatePreviewContext(ctx context.Context, id string, payload *PreviewOptions) (res *Response, err error)

TemplatePreviewContext is the same as TemplatePreview, and it allows the caller to provide a context

func (*Client) TemplatePublish added in v0.2.0

func (c *Client) TemplatePublish(id string) (res *Response, err error)

TemplatePublish publishes a draft template

func (*Client) TemplatePublishContext added in v0.2.0

func (c *Client) TemplatePublishContext(ctx context.Context, id string) (res *Response, err error)

TemplatePublishContext is the same as TemplatePublish, and it allows the caller to provide a context

func (*Client) TemplateUpdate

func (c *Client) TemplateUpdate(t *Template, updatePublished bool) (res *Response, err error)

TemplateUpdate updates a draft/published template with the specified id The `updatePublished` parameter controls which version (draft/false vs published/true) of the template will be updated.

func (*Client) TemplateUpdateContext

func (c *Client) TemplateUpdateContext(ctx context.Context, t *Template, updatePublished bool) (res *Response, err error)

TemplateUpdateContext is the same as TemplateUpdate, and it allows the caller to provide a context

func (*Client) Templates

func (c *Client) Templates() ([]Template, *Response, error)

Templates returns metadata for all Templates in the system.

func (*Client) TemplatesContext

func (c *Client) TemplatesContext(ctx context.Context) (tl []Template, res *Response, err error)

TemplatesContext is the same as Templates, and it allows the caller to provide a context

func (*Client) Transmission

func (c *Client) Transmission(t *Transmission) (*Response, error)

Transmission accepts a Transmission, looks up the record using its ID, and fills out the provided object.

func (*Client) TransmissionContext

func (c *Client) TransmissionContext(ctx context.Context, t *Transmission) (*Response, error)

TransmissionContext is the same as Transmission, and it allows the caller to pass in a context.

func (*Client) TransmissionDelete

func (c *Client) TransmissionDelete(t *Transmission) (*Response, error)

TransmissionDelete attempts to remove the Transmission with the specified id. Only Transmissions which are scheduled for future generation may be deleted.

func (*Client) TransmissionDeleteContext

func (c *Client) TransmissionDeleteContext(ctx context.Context, t *Transmission) (*Response, error)

TransmissionDeleteContext is the same as TransmissionDelete, and it allows the caller to provide a context.

func (*Client) Transmissions

func (c *Client) Transmissions(t *Transmission) ([]Transmission, *Response, error)

Transmissions returns Transmission summary information for matching Transmissions. Filtering by CampaignID (t.CampaignID) and TemplateID (t.ID) is supported.

func (*Client) TransmissionsContext

func (c *Client) TransmissionsContext(ctx context.Context, t *Transmission) ([]Transmission, *Response, error)

TransmissionsContext is the same as Transmissions, and it allows the caller to provide a context.

func (*Client) WebhookDetail

func (c *Client) WebhookDetail(q *WebhookDetailWrapper) (*Response, error)

WebhookDetail updates its argument with details for the specified webhook. https://developers.sparkpost.com/api/#/reference/webhooks/retrieve/retrieve-webhook-details

func (*Client) WebhookDetailContext

func (c *Client) WebhookDetailContext(ctx context.Context, d *WebhookDetailWrapper) (*Response, error)

WebhookDetailContext is the same as WebhookDetail, and allows the caller to specify their own context.

func (*Client) WebhookStatus

func (c *Client) WebhookStatus(s *WebhookStatusWrapper) (*Response, error)

WebhookStatus updates its argument with details of batch delivery for the specified webhook. https://developers.sparkpost.com/api/#/reference/webhooks/batch-status/retrieve-status-information

func (*Client) WebhookStatusContext

func (c *Client) WebhookStatusContext(ctx context.Context, s *WebhookStatusWrapper) (*Response, error)

WebhookStatusContext is the same as WebhookStatus, and allows the caller to specify their own context.

func (*Client) Webhooks

func (c *Client) Webhooks(l *WebhookListWrapper) (*Response, error)

Webhooks updates its argument with a list of all configured webhooks. https://developers.sparkpost.com/api/#/reference/webhooks/list/list-all-webhooks

func (*Client) WebhooksContext

func (c *Client) WebhooksContext(ctx context.Context, l *WebhookListWrapper) (*Response, error)

WebhooksContext is the same as Webhooks, and allows the caller to specify their own context.

type Config

type Config struct {
	BaseUrl    string
	ApiKey     string
	Username   string
	Password   string
	ApiVersion int
	Verbose    bool
}

Config includes all information necessary to make an API request.

func NewConfig

func NewConfig(m map[string]string) (*Config, error)

NewConfig builds a Config object using the provided map.

type Content

type Content struct {
	HTML         string            `json:"html,omitempty"`
	Text         string            `json:"text,omitempty"`
	Subject      string            `json:"subject,omitempty"`
	From         interface{}       `json:"from,omitempty"`
	ReplyTo      string            `json:"reply_to,omitempty"`
	Headers      map[string]string `json:"headers,omitempty"`
	EmailRFC822  string            `json:"email_rfc822,omitempty"`
	Attachments  []Attachment      `json:"attachments,omitempty"`
	InlineImages []InlineImage     `json:"inline_images,omitempty"`
}

Content is what you'll send to your Recipients. Knowledge of SparkPost's substitution/templating capabilities will come in handy here. https://www.sparkpost.com/api#/introduction/substitutions-reference

type ContentToken added in v0.2.0

type ContentToken struct {
	Type TokenType
	Text string
}

ContentToken represents a piece of content, with one of the types defined above.

func Tokenize added in v0.2.0

func Tokenize(str string) (out []ContentToken, err error)

Tokenize splits a string that may contain Handlebars-style template code into (you guessed it) tokens for further processing. Called by Client.ApplyMacros and Recipient.Apply internally. Unless those functions do not meet your specific needs, this function should not need to be called directly.

type ErrorCode added in v0.2.0

type ErrorCode string

ErrorCode is aliased to enable custom UnmarshalJSON

func (ErrorCode) String added in v0.2.0

func (c ErrorCode) String() string

String implements Stringer for ErrorCode, to make it less annoying to print.

func (*ErrorCode) UnmarshalJSON added in v0.2.0

func (c *ErrorCode) UnmarshalJSON(data []byte) error

UnmarshalJSON allows SPError.Code to be either a string or int in JSON returned from the server.

type EventField

type EventField struct {
	Description string      `json:"description"`
	SampleValue interface{} `json:"sampleValue"`
}

type EventGroup

type EventGroup struct {
	Name        string
	Events      map[string]EventMeta `json:"events"`
	Description string               `json:"description"`
	DisplayName string               `json:"display_name"`
}

type EventMeta

type EventMeta struct {
	Name        string
	Fields      map[string]EventField `json:"event"`
	Description string                `json:"description"`
	DisplayName string                `json:"display_name"`
}

type EventsPage

type EventsPage struct {
	Events     events.Events
	TotalCount int
	Errors     []interface{}

	NextPage  string
	PrevPage  string
	FirstPage string
	LastPage  string

	Client *Client           `json:"-"`
	Params map[string]string `json:"-"`
}

func (*EventsPage) Next

func (page *EventsPage) Next() (*EventsPage, *Response, error)

Next returns the next page of results from a previous MessageEventsSearch call

func (*EventsPage) NextContext

func (page *EventsPage) NextContext(ctx context.Context) (*EventsPage, *Response, error)

NextContext is the same as Next, and it accepts a context.Context

func (*EventsPage) UnmarshalJSON

func (page *EventsPage) UnmarshalJSON(data []byte) error

type From

type From struct {
	Email string `json:"email"`
	Name  string `json:"name"`
}

From describes the nested object way of specifying the From header. Content.From can be specified this way, or as a plain string.

func ParseFrom

func ParseFrom(from interface{}) (f From, err error)

ParseFrom parses the various allowable Content.From values.

type InlineImage

type InlineImage Attachment

InlineImage contains metadata and the contents of the image to make available for inline use.

type Macro added in v0.2.0

type Macro struct {
	Name string
	Func func(string) string
}

Macro enables user-defined functions to run on Template.Content before sending to the SparkPost API. This enables e.g. external content, locale-specific date formatting, and so on.

type MetricItem

type MetricItem struct {
	CountInjected               int    `json:"count_injected"`
	CountBounce                 int    `json:"count_bounce,omitempty"`
	CountRejected               int    `json:"count_rejected,omitempty"`
	CountDelivered              int    `json:"count_delivered,omitempty"`
	CountDeliveredFirst         int    `json:"count_delivered_first,omitempty"`
	CountDeliveredSubsequent    int    `json:"count_delivered_subsequent,omitempty"`
	TotalDeliveryTimeFirst      int    `json:"total_delivery_time_first,omitempty"`
	TotalDeliveryTimeSubsequent int    `json:"total_delivery_time_subsequent,omitempty"`
	TotalMsgVolume              int    `json:"total_msg_volume,omitempty"`
	CountPolicyRejection        int    `json:"count_policy_rejection,omitempty"`
	CountGenerationRejection    int    `json:"count_generation_rejection,omitempty"`
	CountGenerationFailed       int    `json:"count_generation_failed,omitempty"`
	CountInbandBounce           int    `json:"count_inband_bounce,omitempty"`
	CountOutofbandBounce        int    `json:"count_outofband_bounce,omitempty"`
	CountSoftBounce             int    `json:"count_soft_bounce,omitempty"`
	CountHardBounce             int    `json:"count_hard_bounce,omitempty"`
	CountBlockBounce            int    `json:"count_block_bounce,omitempty"`
	CountAdminBounce            int    `json:"count_admin_bounce,omitempty"`
	CountUndeterminedBounce     int    `json:"count_undetermined_bounce,omitempty"`
	CountDelayed                int    `json:"count_delayed,omitempty"`
	CountDelayedFirst           int    `json:"count_delayed_first,omitempty"`
	CountRendered               int    `json:"count_rendered,omitempty"`
	CountUniqueRendered         int    `json:"count_unique_rendered,omitempty"`
	CountUniqueConfirmedOpened  int    `json:"count_unique_confirmed_opened,omitempty"`
	CountClicked                int    `json:"count_clicked,omitempty"`
	CountUniqueClicked          int    `json:"count_unique_clicked,omitempty"`
	CountTargeted               int    `json:"count_targeted,omitempty"`
	CountSent                   int    `json:"count_sent,omitempty"`
	CountAccepted               int    `json:"count_accepted,omitempty"`
	CountSpamComplaint          int    `json:"count_spam_complaint,omitempty"`
	Domain                      string `json:"domain,omitempty"`
	CampaignId                  string `json:"campaign_id,omitempty"`
	TemplateId                  string `json:"template_id,omitempty"`
	TimeStamp                   string `json:"ts,omitempty"`
	WatchedDomain               string `json:"watched_domain,omitempty"`
	Binding                     string `json:"binding,omitempty"`
	BindingGroup                string `json:"binding_group,omitempty"`
}

type Metrics

type Metrics struct {
	Results    []MetricItem        `json:"results,omitempty"`
	TotalCount int                 `json:"total_count,omitempty"`
	Links      []map[string]string `json:"links,omitempty"`
	Errors     []interface{}       `json:"errors,omitempty"`

	ExtraPath string            `json:"-"`
	Params    map[string]string `json:"-"`
}

type PreviewOptions

type PreviewOptions struct {
	SubstitutionData map[string]interface{} `json:"substitution_data"`
}

PreviewOptions contains the required subsitution_data object to preview a template

type RFC3339

type RFC3339 time.Time

RFC3339 formats time.Time values as expected by the SparkPost API

func (*RFC3339) MarshalJSON

func (r *RFC3339) MarshalJSON() ([]byte, error)

MarshalJSON applies RFC3339 formatting

type Recipient

type Recipient struct {
	Address          interface{} `json:"address"`
	ReturnPath       string      `json:"return_path,omitempty"`
	Tags             []string    `json:"tags,omitempty"`
	Metadata         interface{} `json:"metadata,omitempty"`
	SubstitutionData interface{} `json:"substitution_data,omitempty"`
}

Recipient represents one email (you guessed it) recipient.

func (*Recipient) Apply added in v0.2.0

func (r *Recipient) Apply(in string) (string, error)

Apply substitutes top-level string values from the Recipient's SubstitutionData and Metadata (in that order) for placeholders in the provided string. Nested substitution blocks will not be interpreted, meaning that they will be passed along to the API.

func (Recipient) Validate

func (r Recipient) Validate() error

Validate runs sanity checks on a Recipient struct. This should catch most errors before attempting a doomed API call.

type RecipientList

type RecipientList struct {
	ID          string      `json:"id,omitempty"`
	Name        string      `json:"name,omitempty"`
	Description string      `json:"description,omitempty"`
	Attributes  interface{} `json:"attributes,omitempty"`
	Recipients  []Recipient `json:"recipients"`

	Accepted *int `json:"total_accepted_recipients,omitempty"`
}

RecipientList is the JSON structure accepted by and returned from the SparkPost Recipient Lists API. It's mostly metadata at this level - see Recipients for more detail.

func (*RecipientList) Validate

func (rl *RecipientList) Validate() error

Validate runs sanity checks on a RecipientList struct. This should catch most errors before attempting a doomed API call.

type Response

type Response struct {
	HTTP    *http.Response
	Body    []byte
	Verbose map[string]string
	Results interface{} `json:"results,omitempty"`
	Errors  SPErrors    `json:"errors,omitempty"`
}

Response contains information about the last HTTP response. Helpful when an error message doesn't necessarily give the complete picture. Also contains any messages emitted as a result of the Verbose config option.

func (*Response) AssertJson

func (r *Response) AssertJson() (body []byte, err error)

AssertJson returns an error if the provided HTTP response isn't JSON.

func (*Response) HTTPError

func (res *Response) HTTPError() error

HTTPError returns nil when the HTTP response code is in the range 200-299. If the API has returned a JSON error in the expected format, return that. Otherwise, return an error containing the HTTP code and response body.

func (*Response) ParseResponse

func (r *Response) ParseResponse() error

ParseResponse pulls info from JSON http responses into api.Response object. It's helpful to call Response.AssertJson before calling this function.

func (*Response) ReadBody

func (r *Response) ReadBody() ([]byte, error)

ReadBody is a convenience method that returns the http.Response body. The first time this function is called, the body is read from the http.Response. For subsequent calls, the cached version in Response.Body is returned.

type SPError

type SPError struct {
	Message     string    `json:"message"`
	Code        ErrorCode `json:"code"`
	Description string    `json:"description"`
	Part        string    `json:"part,omitempty"`
	Line        int       `json:"line,omitempty"`
}

SPError mirrors the error format returned by SparkPost APIs.

type SPErrors

type SPErrors []SPError

SPErrors is the plural of SPError

func (SPErrors) Error

func (e SPErrors) Error() string

Error satisfies the builtin Error interface

type Subaccount

type Subaccount struct {
	ID               int      `json:"id,omitempty"`
	Name             string   `json:"name,omitempty"`
	Key              string   `json:"key,omitempty"`
	KeyLabel         string   `json:"key_label,omitempty"`
	Grants           []string `json:"key_grants,omitempty"`
	ShortKey         string   `json:"short_key,omitempty"`
	Status           string   `json:"status,omitempty"`
	ComplianceStatus string   `json:"compliance_status,omitempty"`
	IPPool           string   `json:"ip_pool,omitempty"`
}

Subaccount is the JSON structure accepted by and returned from the SparkPost Subaccounts API.

type SuppressionEntry

type SuppressionEntry struct {
	// Email is used when list is stored
	Email string `json:"email,omitempty"`

	// Recipient is used when a list is returned
	Recipient string `json:"recipient,omitempty"`

	Transactional    bool   `json:"transactional,omitempty"`
	NonTransactional bool   `json:"non_transactional,omitempty"`
	Source           string `json:"source,omitempty"`
	Type             string `json:"type,omitempty"`
	Description      string `json:"description,omitempty"`
	Updated          string `json:"updated,omitempty"`
	Created          string `json:"created,omitempty"`
}

SuppressionEntry stores a recipient’s opt-out preferences. It is a list of recipient email addresses to which you do NOT want to send email. https://developers.sparkpost.com/api/suppression-list.html#header-list-entry-attributes

type SuppressionPage

type SuppressionPage struct {
	Results    []*SuppressionEntry `json:"results,omitempty"`
	Recipients []SuppressionEntry  `json:"recipients,omitempty"`
	Errors     []struct {
		Message string `json:"message,omitempty"`
	} `json:"errors,omitempty"`

	TotalCount int `json:"total_count,omitempty"`

	NextPage  string
	PrevPage  string
	FirstPage string
	LastPage  string

	Links []struct {
		Href string `json:"href"`
		Rel  string `json:"rel"`
	} `json:"links,omitempty"`

	Params map[string]string `json:"-"`
	// contains filtered or unexported fields
}

SuppressionPage wraps suppression entries and response meta information

func (*SuppressionPage) Next

func (sp *SuppressionPage) Next() (*SuppressionPage, *Response, error)

Next returns the next page of results from a previous MessageEventsSearch call

func (*SuppressionPage) NextContext

func (sp *SuppressionPage) NextContext(ctx context.Context) (*SuppressionPage, *Response, error)

NextContext is the same as Next, and it accepts a context.Context

type Template

type Template struct {
	ID          string       `json:"id,omitempty"`
	Content     Content      `json:"content,omitempty"`
	Published   bool         `json:"published,omitempty"`
	Name        string       `json:"name,omitempty"`
	Description string       `json:"description,omitempty"`
	LastUse     time.Time    `json:"last_use,omitempty"`
	LastUpdate  time.Time    `json:"last_update_time,omitempty"`
	Options     *TmplOptions `json:"options,omitempty"`
}

Template is the JSON structure accepted by and returned from the SparkPost Templates API. It's mostly metadata at this level - see Content and Options for more detail.

Example

ExampleTemplate builds a native Go Template structure from a JSON string

package main

import (
	"encoding/json"

	sp "github.com/SparkPost/gosparkpost"
)

func main() {
	template := &sp.Template{}
	jsonStr := `{
		"name": "testy template",
		"content": {
			"html": "this is a <b>test</b> email!",
			"subject": "test email",
			"from": {
				"name": "tester",
				"email": "tester@example.com"
			},
			"reply_to": "tester@example.com"
		}
	}`
	err := json.Unmarshal([]byte(jsonStr), template)
	if err != nil {
		panic(err)
	}
}
Output:

func (*Template) Validate

func (t *Template) Validate() error

Validate runs sanity checks on a Template struct. This should catch most errors before attempting a doomed API call.

type TmplOptions

type TmplOptions struct {
	OpenTracking  *bool `json:"open_tracking,omitempty"`
	ClickTracking *bool `json:"click_tracking,omitempty"`
	Transactional *bool `json:"transactional,omitempty"`
}

TmplOptions specifies settings to apply to this Template. These settings may be overridden in the Transmission API call.

type TokenType added in v0.2.0

type TokenType int

TokenType differentiates between static content and macros that require extra processing.

type Transmission

type Transmission struct {
	ID               string      `json:"id,omitempty"`
	State            string      `json:"state,omitempty"`
	Options          *TxOptions  `json:"options,omitempty"`
	Recipients       interface{} `json:"recipients"`
	CampaignID       string      `json:"campaign_id,omitempty"`
	Description      string      `json:"description,omitempty"`
	Metadata         interface{} `json:"metadata,omitempty"`
	SubstitutionData interface{} `json:"substitution_data,omitempty"`
	ReturnPath       string      `json:"return_path,omitempty"`
	Content          interface{} `json:"content"`

	TotalRecipients      *int `json:"total_recipients,omitempty"`
	NumGenerated         *int `json:"num_generated,omitempty"`
	NumFailedGeneration  *int `json:"num_failed_generation,omitempty"`
	NumInvalidRecipients *int `json:"num_invalid_recipients,omitempty"`
}

Transmission is the JSON structure accepted by and returned from the SparkPost Transmissions API.

func (*Transmission) Validate

func (t *Transmission) Validate() error

Validate runs sanity checks of a Transmission struct. This should catch most errors before attempting a doomed API call.

type TxOptions

type TxOptions struct {
	TmplOptions

	StartTime            *RFC3339 `json:"start_time,omitempty"`
	Sandbox              *bool    `json:"sandbox,omitempty"`
	SkipSuppression      *bool    `json:"skip_suppression,omitempty"`
	IPPool               string   `json:"ip_pool,omitempty"`
	InlineCSS            *bool    `json:"inline_css,omitempty"`
	PerformSubstitutions *bool    `json:"perform_substitutions,omitempty"`
}

TxOptions specifies settings to apply to this Transmission. If not specified, and present in TmplOptions, those values will be used.

type WebhookCommon

type WebhookCommon struct {
	Errors []interface{}     `json:"errors,omitempty"`
	Params map[string]string `json:"-"`
}

WebhookCommon contains fields common to all response types.

type WebhookDetailWrapper

type WebhookDetailWrapper struct {
	ID      string       `json:"-"`
	Results *WebhookItem `json:"results,omitempty"`
	WebhookCommon
}

WebhookDetailWrapper is passed into and updated by the WebhookDetail method, using results returned from the API.

type WebhookItem

type WebhookItem struct {
	ID       string   `json:"id,omitempty"`
	Name     string   `json:"name,omitempty"`
	Target   string   `json:"target,omitempty"`
	Events   []string `json:"events,omitempty"`
	AuthType string   `json:"auth_type,omitempty"`

	AuthRequestDetails struct {
		URL  string `json:"url,omitempty"`
		Body struct {
			ClientID     string `json:"client_id,omitempty"`
			ClientSecret string `json:"client_secret,omitempty"`
		} `json:"body,omitempty"`
	} `json:"auth_request_details,omitempty"`

	AuthCredentials struct {
		Username    string `json:"username,omitempty"`
		Password    string `json:"password,omitempty"`
		AccessToken string `json:"access_token,omitempty"`
		ExpiresIn   int    `json:"expires_in,omitempty"`
	} `json:"auth_credentials,omitempty"`

	AuthToken      string `json:"auth_token,omitempty"`
	LastSuccessful string `json:"last_successful,omitempty,omitempty"`
	LastFailure    string `json:"last_failure,omitempty,omitempty"`

	Links []struct {
		Href   string   `json:"href,omitempty"`
		Rel    string   `json:"rel,omitempty"`
		Method []string `json:"method,omitempty"`
	} `json:"links,omitempty"`
}

WebhookItem defines how webhook objects will be returned, as well as how they must be sent.

type WebhookListWrapper

type WebhookListWrapper struct {
	Results []WebhookItem `json:"results,omitempty"`
	WebhookCommon
}

WebhookListWrapper is passed into and updated by the Webhooks method, using results returned from the API.

type WebhookStatus

type WebhookStatus struct {
	BatchID      string `json:"batch_id,omitempty"`
	Timestamp    string `json:"ts,omitempty"`
	Attempts     int    `json:"attempts,omitempty"`
	ResponseCode string `json:"response_code,omitempty"`
	FailureCode  string `json:"failure_code,omitempty"`
}

WebhookStatus defines how the status of a webhook will be returned.

type WebhookStatusWrapper

type WebhookStatusWrapper struct {
	ID      string          `json:"-"`
	Results []WebhookStatus `json:"results,omitempty"`
	WebhookCommon
}

WebhookStatusWrapper is passed into and updated by the WebhookStatus method, using results returned from the API.

type WritableSuppressionEntry

type WritableSuppressionEntry struct {
	// Recipient is used when a list is returned
	Recipient   string `json:"recipient,omitempty"`
	Type        string `json:"type,omitempty"`
	Description string `json:"description,omitempty"`
}

WritableSuppressionEntry stores a recipient’s opt-out preferences. It is a list of recipient email addresses to which you do NOT want to send email. https://developers.sparkpost.com/api/suppression-list.html#suppression-list-bulk-insert-update-put

Directories

Path Synopsis
cmd
qp
sparks
Sparks is a command-line tool for quickly sending email using SparkPost.
Sparks is a command-line tool for quickly sending email using SparkPost.
Package events defines a struct for each type of event and provides various other helper functions.
Package events defines a struct for each type of event and provides various other helper functions.
examples
cc
helpers

Jump to

Keyboard shortcuts

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