mailgun

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2016 License: BSD-3-Clause, Apache-2.0 Imports: 8 Imported by: 0

README

Mailgun with Go

Build Status GoDoc

Go library for sending mail with the Mailgun API.

See these examples on how how to use use the library with various parts of the Mailgun API:

More examples are coming soon.

The code is released under a 3-clause BSD license. See the LICENSE file for more information.

Documentation

Overview

The mailgun package provides methods for interacting with the Mailgun API. It automates the HTTP request/response cycle, encodings, and other details needed by the API. This SDK lets you do everything the API lets you, in a more Go-friendly way.

For further information please see the Mailgun documentation at http://documentation.mailgun.com/

Original Author: Michael Banzon
Contributions:   Samuel A. Falvo II <sam.falvo %at% rackspace.com>
Version:         0.99.0

Examples

This document includes a number of examples which illustrates some aspects of the GUI which might be misleading or confusing. All examples included are derived from an acceptance test. Note that every SDK function has a corresponding acceptance test, so if you don't find an example for a function you'd like to know more about, please check the acceptance sub-package for a corresponding test. Of course, contributions to the documentation are always welcome as well. Feel free to submit a pull request or open a Github issue if you cannot find an example to suit your needs.

Limit and Skip Settings

Many SDK functions consume a pair of parameters called limit and skip. These help control how much data Mailgun sends over the wire. Limit, as you'd expect, gives a count of the number of records you want to receive. Note that, at present, Mailgun imposes its own cap of 100, for all API endpoints. Skip indicates where in the data set you want to start receiving from. Mailgun defaults to the very beginning of the dataset if not specified explicitly.

If you don't particularly care how much data you receive, you may specify DefaultLimit. If you similarly don't care about where the data starts, you may specify DefaultSkip.

Functions that Return Totals

Functions which accept a limit and skip setting, in general, will also return a total count of the items returned. Note that this total count is not the total in the bundle returned by the call. You can determine that easily enough with Go's len() function. The total that you receive actually refers to the complete set of data on the server. This total may well exceed the size returned from the API.

If this happens, you may find yourself needing to iterate over the dataset of interest. For example:

// Get total amount of stuff we have to work with.
mg := NewMailgun("example.com", "my_api_key", "")
n, _, err := mg.GetStats(1, 0, nil, "sent", "opened")
if err != nil {
	t.Fatal(err)
}
// Loop over it all.
for sk := 0; sk < n; sk += limit {
	_, stats, err := mg.GetStats(limit, sk, nil, "sent", "opened")
 	if err != nil {
 		t.Fatal(err)
 	}
	doSomethingWith(stats)
}

License

Copyright (c) 2013-2014, Michael Banzon. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the names of Mailgun, Michael Banzon, nor the names of their contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Index

Examples

Constants

View Source
const (
	DefaultLimit = -1
	DefaultSkip  = -1
)

DefaultLimit and DefaultSkip instruct the SDK to rely on Mailgun's reasonable defaults for pagination settings.

View Source
const (
	Tag      = "tag"
	Disabled = "disabled"
	Delete   = "delete"
)

Disabled, Tag, and Delete indicate spam actions. Disabled prevents Mailgun from taking any action on what it perceives to be spam. Tag instruments the received message with headers providing a measure of its spamness. Delete instructs Mailgun to just block or delete the message all-together.

View Source
const (
	ReadOnly = "readonly"
	Members  = "members"
	Everyone = "everyone"
)

A mailing list may have one of three membership modes. ReadOnly specifies that nobody, including Members, may send messages to the mailing list. Messages distributed on such lists come from list administrator accounts only. Members specifies that only those who subscribe to the mailing list may send messages. Everyone specifies that anyone and everyone may both read and submit messages to the mailing list, including non-subscribers.

View Source
const MailgunGoUserAgent = "mailgun-go/1.0.0"

The MailgunGoUserAgent identifies the client to the server, for logging purposes. In the event of problems requiring a human administrator's assistance, this user agent allows them to identify the client from human-generated activity.

View Source
const MaxNumberOfRecipients = 1000

MaxNumberOfRecipients represents the largest batch of recipients that Mailgun can support in a single API call. This figure includes To:, Cc:, Bcc:, etc. recipients.

Variables

View Source
var (
	All          *bool = nil
	Subscribed   *bool = &yes
	Unsubscribed *bool = &no
)

Mailing list members have an attribute that determines if they've subscribed to the mailing list or not. This attribute may be used to filter the results returned by GetSubscribers(). All, Subscribed, and Unsubscribed provides a convenient and readable syntax for specifying the scope of the search.

View Source
var ErrEmptyParam = fmt.Errorf("empty or illegal parameter")

ErrEmptyParam results occur when a required parameter is missing.

Functions

This section is empty.

Types

type Bounce

type Bounce struct {
	CreatedAt string `json:"created_at"`

	Address string `json:"address"`
	Error   string `json:"error"`
	// contains filtered or unexported fields
}

Bounce aggregates data relating to undeliverable messages to a specific intended recipient, identified by Address. Code provides the SMTP error code causing the bounce, while Error provides a human readable reason why. CreatedAt provides the time at which Mailgun detected the bounce.

func (Bounce) GetCode

func (b Bounce) GetCode() (int, error)

GetCode will return the bounce code for the message, regardless if it was returned as a string or as an integer. This method overcomes a protocol bug in the Mailgun API.

func (Bounce) GetCreatedAt

func (i Bounce) GetCreatedAt() (t time.Time, err error)

GetCreatedAt parses the textual, RFC-822 timestamp into a standard Go-compatible Time structure.

type Campaign

type Campaign struct {
	Id                string `json:"id"`
	Name              string `json:"name"`
	CreatedAt         string `json:"created_at"`
	DeliveredCount    int    `json:"delivered_count"`
	ClickedCount      int    `json:"clicked_count"`
	OpenedCount       int    `json:"opened_count"`
	SubmittedCount    int    `json:"submitted_count"`
	UnsubscribedCount int    `json:"unsubscribed_count"`
	BouncedCount      int    `json:"bounced_count"`
	ComplainedCount   int    `json:"complained_count"`
	DroppedCount      int    `json:"dropped_count"`
}

Campaigns have been deprecated since development work on this SDK commenced. Please refer to http://documentation.mailgun.com/api_reference .

type Complaint

type Complaint struct {
	Count     int    `json:"count"`
	CreatedAt string `json:"created_at"`
	Address   string `json:"address"`
}

Complaint structures track how many times one of your emails have been marked as spam. CreatedAt indicates when the first report arrives from a given recipient, identified by Address. Count provides a running counter of how many times the recipient thought your messages were not solicited.

type Credential

type Credential struct {
	CreatedAt string `json:"created_at"`
	Login     string `json:"login"`
	Password  string `json:"password"`
}

A Credential structure describes a principle allowed to send or receive mail at the domain.

type DNSRecord

type DNSRecord struct {
	Priority   string
	RecordType string `json:"record_type"`
	Valid      string
	Name       string
	Value      string
}

DNSRecord structures describe intended records to properly configure your domain for use with Mailgun. Note that Mailgun does not host DNS records.

type Domain

type Domain struct {
	CreatedAt    string `json:"created_at"`
	SMTPLogin    string `json:"smtp_login"`
	Name         string `json:"name"`
	SMTPPassword string `json:"smtp_password"`
	Wildcard     bool   `json:"wildcard"`
	SpamAction   string `json:"spam_action"`
}

A Domain structure holds information about a domain used when sending mail. The SpamAction field must be one of Tag, Disabled, or Delete.

func (Domain) GetCreatedAt

func (d Domain) GetCreatedAt() (t time.Time, err error)

GetCreatedAt returns the time the domain was created as a normal Go time.Time type.

type EmailVerification

type EmailVerification struct {
	IsValid    bool                   `json:"is_valid"`
	Parts      EmailVerificationParts `json:"parts"`
	Address    string                 `json:"address"`
	DidYouMean string                 `json:"did_you_mean"`
}

EmailVerification records basic facts about a validated e-mail address. See the ValidateEmail method and example for more details.

IsValid indicates whether an email address conforms to IETF RFC standards. Parts records the different subfields of an email address. Address echoes the address provided. DidYouMean provides a simple recommendation in case the address is invalid or Mailgun thinks you might have a typo. DidYouMean may be empty (""), in which case Mailgun has no recommendation to give. The existence of DidYouMean does NOT imply the email provided has anything wrong with it.

type EmailVerificationParts

type EmailVerificationParts struct {
	LocalPart   string `json:"local_part"`
	Domain      string `json:"domain"`
	DisplayName string `json:"display_name"`
}

The EmailVerificationParts structure breaks out the basic elements of an email address. LocalPart includes everything up to the '@' in an e-mail address. Domain includes everything after the '@'. DisplayName is no longer used, and will appear as "".

type Event

type Event map[string]interface{}

Events are open-ended, loosely-defined JSON documents. They will always have an event and a timestamp field, however.

type EventIterator

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

EventIterator maintains the state necessary for paging though small parcels of a larger set of events.

func (*EventIterator) Events

func (ei *EventIterator) Events() []Event

Events returns the most recently retrieved batch of events. The length is guaranteed to fall between 0 and the limit set in the GetEventsOptions structure passed to GetFirstPage.

func (*EventIterator) GetFirstPage

func (ei *EventIterator) GetFirstPage(opts GetEventsOptions) error

GetFirstPage retrieves the first batch of events, according to your criteria. See the GetEventsOptions structure for more details on how the fields affect the data returned.

func (*EventIterator) GetNext

func (ei *EventIterator) GetNext() error

Retrieves the chronologically next batch of events, if any exist. You know you're at the end of the list when len(Events())==0.

func (*EventIterator) GetPrevious

func (ei *EventIterator) GetPrevious() error

Retrieves the chronologically previous batch of events, if any exist. You know you're at the end of the list when len(Events())==0.

type GetEventsOptions

type GetEventsOptions struct {
	Begin, End                               time.Time
	ForceAscending, ForceDescending, Compact bool
	Limit                                    int
	Filter                                   map[string]string
}

GetEventsOptions lets the caller of GetEvents() specify how the results are to be returned. Begin and End time-box the results returned. ForceAscending and ForceDescending are used to force Mailgun to use a given traversal order of the events. If both ForceAscending and ForceDescending are true, an error will result. If none, the default will be inferred from the Begin and End parameters. Limit caps the number of results returned. If left unspecified, Mailgun assumes 100. Compact, if true, compacts the returned JSON to minimize transmission bandwidth. Otherwise, the JSON is spaced appropriately for human consumption. Filter allows the caller to provide more specialized filters on the query. Consult the Mailgun documentation for more details.

type List

type List struct {
	Address      string `json:"address",omitempty"`
	Name         string `json:"name",omitempty"`
	Description  string `json:"description",omitempty"`
	AccessLevel  string `json:"access_level",omitempty"`
	CreatedAt    string `json:"created_at",omitempty"`
	MembersCount int    `json:"members_count",omitempty"`
}

A List structure provides information for a mailing list.

AccessLevel may be one of ReadOnly, Members, or Everyone.

type Mailgun

type Mailgun interface {
	Domain() string
	ApiKey() string
	PublicApiKey() string
	Send(m *Message) (string, string, error)
	ValidateEmail(email string) (EmailVerification, error)
	ParseAddresses(addresses ...string) ([]string, []string, error)
	GetBounces(limit, skip int) (int, []Bounce, error)
	GetSingleBounce(address string) (Bounce, error)
	AddBounce(address, code, error string) error
	DeleteBounce(address string) error
	GetStats(limit int, skip int, startDate *time.Time, event ...string) (int, []Stat, error)
	DeleteTag(tag string) error
	GetDomains(limit, skip int) (int, []Domain, error)
	GetSingleDomain(domain string) (Domain, []DNSRecord, []DNSRecord, error)
	CreateDomain(name string, smtpPassword string, spamAction string, wildcard bool) error
	DeleteDomain(name string) error
	GetCampaigns() (int, []Campaign, error)
	CreateCampaign(name, id string) error
	UpdateCampaign(oldId, name, newId string) error
	DeleteCampaign(id string) error
	GetComplaints(limit, skip int) (int, []Complaint, error)
	GetSingleComplaint(address string) (Complaint, error)
	GetStoredMessage(id string) (StoredMessage, error)
	GetStoredMessageRaw(id string) (StoredMessageRaw, error)
	DeleteStoredMessage(id string) error
	GetCredentials(limit, skip int) (int, []Credential, error)
	CreateCredential(login, password string) error
	ChangeCredentialPassword(id, password string) error
	DeleteCredential(id string) error
	GetUnsubscribes(limit, skip int) (int, []Unsubscription, error)
	GetUnsubscribesByAddress(string) (int, []Unsubscription, error)
	Unsubscribe(address, tag string) error
	RemoveUnsubscribe(string) error
	CreateComplaint(string) error
	DeleteComplaint(string) error
	GetRoutes(limit, skip int) (int, []Route, error)
	GetRouteByID(string) (Route, error)
	CreateRoute(Route) (Route, error)
	DeleteRoute(string) error
	UpdateRoute(string, Route) (Route, error)
	GetWebhooks() (map[string]string, error)
	CreateWebhook(kind, url string) error
	DeleteWebhook(kind string) error
	GetWebhookByType(kind string) (string, error)
	UpdateWebhook(kind, url string) error
	GetLists(limit, skip int, filter string) (int, []List, error)
	CreateList(List) (List, error)
	DeleteList(string) error
	GetListByAddress(string) (List, error)
	UpdateList(string, List) (List, error)
	GetMembers(limit, skip int, subfilter *bool, address string) (int, []Member, error)
	GetMemberByAddress(MemberAddr, listAddr string) (Member, error)
	CreateMember(merge bool, addr string, prototype Member) error
	CreateMemberList(subscribed *bool, addr string, newMembers []interface{}) error
	UpdateMember(Member, list string, prototype Member) (Member, error)
	DeleteMember(Member, list string) error
	NewMessage(from, subject, text string, to ...string) *Message
	NewMIMEMessage(body io.ReadCloser, to ...string) *Message
	NewEventIterator() *EventIterator
}

Mailgun defines the supported subset of the Mailgun API. The Mailgun API may contain additional features which have been deprecated since writing this SDK. This SDK only covers currently supported interface endpoints.

Note that Mailgun reserves the right to deprecate endpoints. Some endpoints listed in this interface may, at any time, become obsolete. Always double-check with the Mailgun API Documentation to determine the currently supported feature set.

func NewMailgun

func NewMailgun(domain, apiKey, publicApiKey string) Mailgun

NewMailGun creates a new client instance.

type MailgunImpl

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

MailgunImpl bundles data needed by a large number of methods in order to interact with the Mailgun API. Colloquially, we refer to instances of this structure as "clients."

func (*MailgunImpl) AddBounce

func (m *MailgunImpl) AddBounce(address, code, error string) error

AddBounce files a bounce report. Address identifies the intended recipient of the message that bounced. Code corresponds to the numeric response given by the e-mail server which rejected the message. Error providees the corresponding human readable reason for the problem. For example, here's how the these two fields relate. Suppose the SMTP server responds with an error, as below. Then, . . .

 550  Requested action not taken: mailbox unavailable
\___/\_______________________________________________/
  |                         |
  `-- Code                  `-- Error

Note that both code and error exist as strings, even though code will report as a number.

func (*MailgunImpl) ApiKey

func (m *MailgunImpl) ApiKey() string

ApiKey returns the API key configured for this client.

func (*MailgunImpl) ChangeCredentialPassword

func (mg *MailgunImpl) ChangeCredentialPassword(id, password string) error

ChangeCredentialPassword attempts to alter the indicated credential's password.

func (*MailgunImpl) CreateCampaign

func (m *MailgunImpl) CreateCampaign(name, id string) error

Campaigns have been deprecated since development work on this SDK commenced. Please refer to http://documentation.mailgun.com/api_reference .

func (*MailgunImpl) CreateComplaint

func (m *MailgunImpl) CreateComplaint(address string) error

CreateComplaint registers the specified address as a recipient who has complained of receiving spam from your domain.

func (*MailgunImpl) CreateCredential

func (mg *MailgunImpl) CreateCredential(login, password string) error

CreateCredential attempts to create associate a new principle with your domain.

func (*MailgunImpl) CreateDomain

func (m *MailgunImpl) CreateDomain(name string, smtpPassword string, spamAction string, wildcard bool) error

CreateDomain instructs Mailgun to create a new domain for your account. The name parameter identifies the domain. The smtpPassword parameter provides an access credential for the domain. The spamAction domain must be one of Delete, Tag, or Disabled. The wildcard parameter instructs Mailgun to treat all subdomains of this domain uniformly if true, and as different domains if false.

func (*MailgunImpl) CreateList

func (mg *MailgunImpl) CreateList(prototype List) (List, error)

CreateList creates a new mailing list under your Mailgun account. You need specify only the Address and Name members of the prototype; Description, and AccessLevel are optional. If unspecified, Description remains blank, while AccessLevel defaults to Everyone.

func (*MailgunImpl) CreateMember

func (mg *MailgunImpl) CreateMember(merge bool, addr string, prototype Member) error

CreateMember registers a new member of the indicated mailing list. If merge is set to true, then the registration may update an existing Member's settings. Otherwise, an error will occur if you attempt to add a member with a duplicate e-mail address.

func (*MailgunImpl) CreateMemberList

func (mg *MailgunImpl) CreateMemberList(s *bool, addr string, newMembers []interface{}) error

CreateMemberList registers multiple Members and non-Member members to a single mailing list in a single round-trip. s indicates the default subscribed status (Subscribed or Unsubscribed). Use All to elect not to provide a default. The newMembers list can take one of two JSON-encodable forms: an slice of strings, or a slice of Member structures. If a simple slice of strings is passed, each string refers to the member's e-mail address. Otherwise, each Member needs to have at least the Address field filled out. Other fields are optional, but may be set according to your needs.

func (*MailgunImpl) CreateRoute

func (mg *MailgunImpl) CreateRoute(prototype Route) (Route, error)

CreateRoute installs a new route for your domain. The route structure you provide serves as a template, and only a subset of the fields influence the operation. See the Route structure definition for more details.

func (*MailgunImpl) CreateWebhook

func (mg *MailgunImpl) CreateWebhook(t, u string) error

CreateWebhook installs a new webhook for your domain.

func (*MailgunImpl) DeleteBounce

func (m *MailgunImpl) DeleteBounce(address string) error

DeleteBounce removes all bounces associted with the provided e-mail address.

func (*MailgunImpl) DeleteCampaign

func (m *MailgunImpl) DeleteCampaign(id string) error

Campaigns have been deprecated since development work on this SDK commenced. Please refer to http://documentation.mailgun.com/api_reference .

func (*MailgunImpl) DeleteComplaint

func (m *MailgunImpl) DeleteComplaint(address string) error

DeleteComplaint removes a previously registered e-mail address from the list of people who complained of receiving spam from your domain.

func (*MailgunImpl) DeleteCredential

func (mg *MailgunImpl) DeleteCredential(id string) error

DeleteCredential attempts to remove the indicated principle from the domain.

func (*MailgunImpl) DeleteDomain

func (m *MailgunImpl) DeleteDomain(name string) error

DeleteDomain instructs Mailgun to dispose of the named domain name.

func (*MailgunImpl) DeleteList

func (mg *MailgunImpl) DeleteList(addr string) error

DeleteList removes all current members of the list, then removes the list itself. Attempts to send e-mail to the list will fail subsequent to this call.

func (*MailgunImpl) DeleteMember

func (mg *MailgunImpl) DeleteMember(member, addr string) error

DeleteMember removes the member from the list.

func (*MailgunImpl) DeleteRoute

func (mg *MailgunImpl) DeleteRoute(id string) error

DeleteRoute removes the specified route from your domain's configuration. To avoid ambiguity, Mailgun identifies the route by unique ID. See the Route structure definition and the Mailgun API documentation for more details.

func (*MailgunImpl) DeleteStoredMessage

func (mg *MailgunImpl) DeleteStoredMessage(id string) error

DeleteStoredMessage removes a previously stored message. Note that Mailgun institutes a policy of automatically deleting messages after a set time. Consult the current Mailgun API documentation for more details.

func (*MailgunImpl) DeleteTag

func (m *MailgunImpl) DeleteTag(tag string) error

DeleteTag removes all counters for a particular tag, including the tag itself.

func (*MailgunImpl) DeleteWebhook

func (mg *MailgunImpl) DeleteWebhook(t string) error

DeleteWebhook removes the specified webhook from your domain's configuration.

func (*MailgunImpl) Domain

func (m *MailgunImpl) Domain() string

Domain returns the domain configured for this client.

func (*MailgunImpl) GetBounces

func (m *MailgunImpl) GetBounces(limit, skip int) (int, []Bounce, error)

GetBounces returns a complete set of bounces logged against the sender's domain, if any. The results include the total number of bounces (regardless of skip or limit settings), and the slice of bounces specified, if successful. Note that the length of the slice may be smaller than the total number of bounces.

func (*MailgunImpl) GetCampaigns

func (m *MailgunImpl) GetCampaigns() (int, []Campaign, error)

Campaigns have been deprecated since development work on this SDK commenced. Please refer to http://documentation.mailgun.com/api_reference .

func (*MailgunImpl) GetComplaints

func (m *MailgunImpl) GetComplaints(limit, skip int) (int, []Complaint, error)

GetComplaints returns a set of spam complaints registered against your domain. Recipients of your messages can click on a link which sends feedback to Mailgun indicating that the message they received is, to them, spam.

func (*MailgunImpl) GetCredentials

func (mg *MailgunImpl) GetCredentials(limit, skip int) (int, []Credential, error)

GetCredentials returns the (possibly zero-length) list of credentials associated with your domain.

func (*MailgunImpl) GetDomains

func (m *MailgunImpl) GetDomains(limit, skip int) (int, []Domain, error)

GetDomains retrieves a set of domains from Mailgun.

Assuming no error, both the number of items retrieved and a slice of Domain instances. The number of items returned may be less than the specified limit, if it's specified. Note that zero items and a zero-length slice do not necessarily imply an error occurred. Except for the error itself, all results are undefined in the event of an error.

func (*MailgunImpl) GetListByAddress

func (mg *MailgunImpl) GetListByAddress(addr string) (List, error)

GetListByAddress allows your application to recover the complete List structure representing a mailing list, so long as you have its e-mail address.

func (*MailgunImpl) GetLists

func (mg *MailgunImpl) GetLists(limit, skip int, filter string) (int, []List, error)

GetLists returns the specified set of mailing lists administered by your account.

func (*MailgunImpl) GetMemberByAddress

func (mg *MailgunImpl) GetMemberByAddress(s, l string) (Member, error)

GetMemberByAddress returns a complete Member structure for a member of a mailing list, given only their subscription e-mail address.

func (*MailgunImpl) GetMembers

func (mg *MailgunImpl) GetMembers(limit, skip int, s *bool, addr string) (int, []Member, error)

GetMembers returns the list of members belonging to the indicated mailing list. The s parameter can be set to one of three settings to help narrow the returned data set: All indicates that you want both Members and unsubscribed members alike, while Subscribed and Unsubscribed indicate you want only those eponymous subsets.

func (*MailgunImpl) GetRouteByID

func (mg *MailgunImpl) GetRouteByID(id string) (Route, error)

GetRouteByID retrieves the complete route definition associated with the unique route ID.

func (*MailgunImpl) GetRoutes

func (mg *MailgunImpl) GetRoutes(limit, skip int) (int, []Route, error)

GetRoutes returns the complete set of routes configured for your domain. You use routes to configure how to handle returned messages, or messages sent to a specfic address on your domain. See the Mailgun documentation for more information.

Example
mg := NewMailgun("example.com", "my_api_key", "")
n, routes, err := mg.GetRoutes(DefaultLimit, DefaultSkip)
if err != nil {
	log.Fatal(err)
}
if n > len(routes) {
	log.Printf("More routes exist than has been returned.")
}
for _, r := range routes {
	log.Printf("Route pri=%d expr=%s desc=%s", r.Priority, r.Expression, r.Description)
}
Output:

func (*MailgunImpl) GetSingleBounce

func (m *MailgunImpl) GetSingleBounce(address string) (Bounce, error)

GetSingleBounce retrieves a single bounce record, if any exist, for the given recipient address.

func (*MailgunImpl) GetSingleComplaint

func (m *MailgunImpl) GetSingleComplaint(address string) (Complaint, error)

GetSingleComplaint returns a single complaint record filed by a recipient at the email address provided. If no complaint exists, the Complaint instance returned will be empty.

func (*MailgunImpl) GetSingleDomain

func (m *MailgunImpl) GetSingleDomain(domain string) (Domain, []DNSRecord, []DNSRecord, error)

Retrieve detailed information about the named domain.

func (*MailgunImpl) GetStats

func (m *MailgunImpl) GetStats(limit int, skip int, startDate *time.Time, event ...string) (int, []Stat, error)

GetStats returns a basic set of statistics for different events. Events start at the given start date, if one is provided. If not, this function will consider all stated events dating to the creation of the sending domain.

func (*MailgunImpl) GetStoredMessage

func (mg *MailgunImpl) GetStoredMessage(id string) (StoredMessage, error)

GetStoredMessage retrieves information about a received e-mail message. This provides visibility into, e.g., replies to a message sent to a mailing list.

func (*MailgunImpl) GetStoredMessageRaw

func (mg *MailgunImpl) GetStoredMessageRaw(id string) (StoredMessageRaw, error)

GetStoredMessageRaw retrieves the raw MIME body of a received e-mail message. Compared to GetStoredMessage, it gives access to the unparsed MIME body, and thus delegates to the caller the required parsing.

func (*MailgunImpl) GetUnsubscribes

func (mg *MailgunImpl) GetUnsubscribes(limit, skip int) (int, []Unsubscription, error)

GetUnsubscribes retrieves a list of unsubscriptions issued by recipients of mail from your domain. Zero is a valid list length.

func (*MailgunImpl) GetUnsubscribesByAddress

func (mg *MailgunImpl) GetUnsubscribesByAddress(a string) (int, []Unsubscription, error)

GetUnsubscribesByAddress retrieves a list of unsubscriptions by recipient address. Zero is a valid list length.

func (*MailgunImpl) GetWebhookByType

func (mg *MailgunImpl) GetWebhookByType(t string) (string, error)

GetWebhookByType retrieves the currently assigned webhook URL associated with the provided type of webhook.

func (*MailgunImpl) GetWebhooks

func (mg *MailgunImpl) GetWebhooks() (map[string]string, error)

GetWebhooks returns the complete set of webhooks configured for your domain. Note that a zero-length mapping is not an error.

func (*MailgunImpl) NewEventIterator

func (mg *MailgunImpl) NewEventIterator() *EventIterator

NewEventIterator creates a new iterator for events. Use GetFirstPage to retrieve the first batch of events. Use Next and Previous thereafter as appropriate to iterate through sets of data.

func (*MailgunImpl) NewMIMEMessage

func (mg *MailgunImpl) NewMIMEMessage(body io.ReadCloser, to ...string) *Message

NewMIMEMessage creates a new MIME message. These messages are largely canned; you do not need to invoke setters to set message-related headers. However, you do still need to call setters for Mailgun-specific settings.

Unlike the global function, this method supports arbitrary-sized recipient lists by automatically sending mail in batches of up to MaxNumberOfRecipients.

To support batch sending, you don't want to provide a fixed To: header at this point. Pass nil as the to parameter to skip adding the To: header at this stage. You can do this explicitly, or implicitly, as follows:

// Note absence of To parameter(s)!
m := mg.NewMessage("me@example.com", "Help save our planet", "Hello world!")

Note that you'll need to invoke the AddRecipientAndVariables or AddRecipient method before sending, though.

func (*MailgunImpl) NewMessage

func (mg *MailgunImpl) NewMessage(from, subject, text string, to ...string) *Message

NewMessage returns a new e-mail message with the simplest envelop needed to send.

Unlike the global function, this method supports arbitrary-sized recipient lists by automatically sending mail in batches of up to MaxNumberOfRecipients.

To support batch sending, you don't want to provide a fixed To: header at this point. Pass nil as the to parameter to skip adding the To: header at this stage. You can do this explicitly, or implicitly, as follows:

// Note absence of To parameter(s)!
m := mg.NewMessage("me@example.com", "Help save our planet", "Hello world!")

Note that you'll need to invoke the AddRecipientAndVariables or AddRecipient method before sending, though.

func (*MailgunImpl) ParseAddresses

func (m *MailgunImpl) ParseAddresses(addresses ...string) ([]string, []string, error)

ParseAddresses takes a list of addresses and sorts them into valid and invalid address categories. NOTE: Use of this function requires a proper public API key. The private API key will not work.

Example
mg := NewMailgun("example.com", "", "my_public_api_key")
addressesThatParsed, unparsableAddresses, err := mg.ParseAddresses("Alice <alice@example.com>", "bob@example.com", "example.com")
if err != nil {
	log.Fatal(err)
}
hittest := map[string]bool{
	"Alice <alice@example.com>": true,
	"bob@example.com":           true,
}
for _, a := range addressesThatParsed {
	if !hittest[a] {
		log.Fatalf("Expected %s to be parsable", a)
	}
}
if len(unparsableAddresses) != 1 {
	log.Fatalf("Expected 1 address to be unparsable; got %d", len(unparsableAddresses))
}
Output:

func (*MailgunImpl) PublicApiKey

func (m *MailgunImpl) PublicApiKey() string

PublicApiKey returns the public API key configured for this client.

func (*MailgunImpl) RemoveUnsubscribe

func (mg *MailgunImpl) RemoveUnsubscribe(a string) error

RemoveUnsubscribe removes the e-mail address given from the domain's unsubscription table. If passing in an ID (discoverable from, e.g., GetUnsubscribes()), the e-mail address associated with the given ID will be removed.

func (*MailgunImpl) Send

func (m *MailgunImpl) Send(message *Message) (mes string, id string, err error)

Send attempts to queue a message (see Message, NewMessage, and its methods) for delivery. It returns the Mailgun server response, which consists of two components: a human-readable status message, and a message ID. The status and message ID are set only if no error occurred.

Example (Constructed)
mg := NewMailgun("example.com", "my_api_key", "")
m := NewMessage(
	"Excited User <me@example.com>",
	"Hello World",
	"Testing some Mailgun Awesomeness!",
	"baz@example.com",
	"bar@example.com",
)
m.SetTracking(true)
m.SetDeliveryTime(time.Now().Add(24 * time.Hour))
m.SetHtml("<html><body><h1>Testing some Mailgun Awesomeness!!</h1></body></html>")
_, id, err := mg.Send(m)
if err != nil {
	log.Fatal(err)
}
log.Printf("Message id=%s", id)
Output:

Example (Mime)
exampleMime := `Content-Type: text/plain; charset="ascii"
Subject: Joe's Example Subject
From: Joe Example <joe@example.com>
To: BARGLEGARF <bargle.garf@example.com>
Content-Transfer-Encoding: 7bit
Date: Thu, 6 Mar 2014 00:37:52 +0000

Testing some Mailgun MIME awesomeness!
`
mg := NewMailgun("example.com", "my_api_key", "")
m := NewMIMEMessage(ioutil.NopCloser(strings.NewReader(exampleMime)), "bargle.garf@example.com")
_, id, err := mg.Send(m)
if err != nil {
	log.Fatal(err)
}
log.Printf("Message id=%s", id)
Output:

func (*MailgunImpl) Unsubscribe

func (mg *MailgunImpl) Unsubscribe(a, t string) error

Unsubscribe adds an e-mail address to the domain's unsubscription table.

func (*MailgunImpl) UpdateCampaign

func (m *MailgunImpl) UpdateCampaign(oldId, name, newId string) error

Campaigns have been deprecated since development work on this SDK commenced. Please refer to http://documentation.mailgun.com/api_reference .

func (*MailgunImpl) UpdateList

func (mg *MailgunImpl) UpdateList(addr string, prototype List) (List, error)

UpdateList allows you to change various attributes of a list. Address, Name, Description, and AccessLevel are all optional; only those fields which are set in the prototype will change.

Be careful! If changing the address of a mailing list, e-mail sent to the old address will not succeed. Make sure you account for the change accordingly.

Example
mg := NewMailgun("example.com", "my_api_key", "")
_, err := mg.UpdateList("joe-stat@example.com", List{
	Name:        "Joe Stat",
	Description: "Joe's status report list",
})
if err != nil {
	log.Fatal(err)
}
Output:

func (*MailgunImpl) UpdateMember

func (mg *MailgunImpl) UpdateMember(s, l string, prototype Member) (Member, error)

UpdateMember lets you change certain details about the indicated mailing list member. Address, Name, Vars, and Subscribed fields may be changed.

func (*MailgunImpl) UpdateRoute

func (mg *MailgunImpl) UpdateRoute(id string, route Route) (Route, error)

UpdateRoute provides an "in-place" update of the specified route. Only those route fields which are non-zero or non-empty are updated. All other fields remain as-is.

Example
mg := NewMailgun("example.com", "my_api_key", "")
_, err := mg.UpdateRoute("route-id-here", Route{
	Priority: 2,
})
if err != nil {
	log.Fatal(err)
}
Output:

func (*MailgunImpl) UpdateWebhook

func (mg *MailgunImpl) UpdateWebhook(t, u string) error

UpdateWebhook replaces one webhook setting for another.

func (*MailgunImpl) ValidateEmail

func (m *MailgunImpl) ValidateEmail(email string) (EmailVerification, error)

ValidateEmail performs various checks on the email address provided to ensure it's correctly formatted. It may also be used to break an email address into its sub-components. (See example.) NOTE: Use of this function requires a proper public API key. The private API key will not work.

Example
mg := NewMailgun("example.com", "", "my_public_api_key")
ev, err := mg.ValidateEmail("joe@example.com")
if err != nil {
	log.Fatal(err)
}
if !ev.IsValid {
	log.Fatal("Expected valid e-mail address")
}
log.Printf("Parts local_part=%s domain=%s display_name=%s", ev.Parts.LocalPart, ev.Parts.Domain, ev.Parts.DisplayName)
if ev.DidYouMean != "" {
	log.Printf("The address is syntactically valid, but perhaps has a typo.")
	log.Printf("Did you mean %s instead?", ev.DidYouMean)
}
Output:

type Member

type Member struct {
	Address    string                 `json:"address,omitempty"`
	Name       string                 `json:"name,omitempty"`
	Subscribed *bool                  `json:"subscribed,omitempty"`
	Vars       map[string]interface{} `json:"vars,omitempty"`
}

A Member structure represents a member of the mailing list. The Vars field can represent any JSON-encodable data.

type Message

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

Message structures contain both the message text and the envelop for an e-mail message.

func NewMIMEMessage

func NewMIMEMessage(body io.ReadCloser, to ...string) *Message

NewMIMEMessage creates a new MIME message. These messages are largely canned; you do not need to invoke setters to set message-related headers. However, you do still need to call setters for Mailgun-specific settings.

DEPRECATED. The package will panic if you use AddRecipient(), AddBcc(), AddCc(), et. al. on a message already equipped with MaxNumberOfRecipients recipients. Use Mailgun.NewMIMEMessage() instead. It works similarly to this function, but supports larger lists of recipients.

func NewMessage

func NewMessage(from string, subject string, text string, to ...string) *Message

NewMessage returns a new e-mail message with the simplest envelop needed to send.

DEPRECATED. The package will panic if you use AddRecipient(), AddBcc(), AddCc(), et. al. on a message already equipped with MaxNumberOfRecipients recipients. Use Mailgun.NewMessage() instead. It works similarly to this function, but supports larger lists of recipients.

func (*Message) AddAttachment

func (m *Message) AddAttachment(attachment string)

AddAttachment arranges to send a file from the filesystem along with the e-mail message. The attachment parameter is a filename, which must refer to a file which actually resides in the local filesystem.

func (*Message) AddBCC

func (m *Message) AddBCC(recipient string)

AddBCC appends a receiver to the blind-carbon-copy header of a message.

func (*Message) AddCC

func (m *Message) AddCC(recipient string)

AddCC appends a receiver to the carbon-copy header of a message.

func (*Message) AddCampaign

func (m *Message) AddCampaign(campaign string)

This feature is deprecated for new software.

func (*Message) AddHeader

func (m *Message) AddHeader(header, value string)

AddHeader allows you to send custom MIME headers with the message.

func (*Message) AddInline

func (m *Message) AddInline(inline string)

AddInline arranges to send a file along with the e-mail message, but does so in a way that its data remains "inline" with the rest of the message. This can be used to send image or font data along with an HTML-encoded message body. The attachment parameter is a filename, which must refer to a file which actually resides in the local filesystem.

func (*Message) AddReaderAttachment

func (m *Message) AddReaderAttachment(filename string, readCloser io.ReadCloser)

AddReaderAttachment arranges to send a file along with the e-mail message. File contents are read from a io.ReadCloser. The filename parameter is the resulting filename of the attachment. The readCloser parameter is the io.ReadCloser which reads the actual bytes to be used as the contents of the attached file.

func (*Message) AddRecipient

func (m *Message) AddRecipient(recipient string) error

AddRecipient appends a receiver to the To: header of a message.

NOTE: Above a certain limit (currently 1000 recipients), this function will cause the message as it's currently defined to be sent. This allows you to support large mailing lists without running into Mailgun's API limitations.

func (*Message) AddRecipientAndVariables

func (m *Message) AddRecipientAndVariables(r string, vars map[string]interface{}) error

AddRecipientAndVariables appends a receiver to the To: header of a message, and as well attaches a set of variables relevant for this recipient.

NOTE: Above a certain limit (see MaxNumberOfRecipients), this function will cause the message as it's currently defined to be sent. This allows you to support large mailing lists without running into Mailgun's API limitations.

func (*Message) AddTag

func (m *Message) AddTag(tag string)

AddTag attaches a tag to the message. Tags are useful for metrics gathering and event tracking purposes. Refer to the Mailgun documentation for further details.

func (*Message) AddVariable

func (m *Message) AddVariable(variable string, value interface{}) error

AddVariable lets you associate a set of variables with messages you send, which Mailgun can use to, in essence, complete form-mail. Refer to the Mailgun documentation for more information.

func (*Message) EnableTestMode

func (m *Message) EnableTestMode()

EnableTestMode allows submittal of a message, such that it will be discarded by Mailgun. This facilitates testing client-side software without actually consuming e-mail resources.

func (*Message) RecipientCount

func (m *Message) RecipientCount() int

RecipientCount returns the total number of recipients for the message. This includes To:, Cc:, and Bcc: fields.

NOTE: At present, this method is reliable only for non-MIME messages, as the Bcc: and Cc: fields are easily accessible. For MIME messages, only the To: field is considered. A fix for this issue is planned for a future release. For now, MIME messages are always assumed to have 10 recipients between Cc: and Bcc: fields. If your MIME messages have more than 10 non-To: field recipients, you may find that some recipients will not receive your e-mail. It's perfectly OK, of course, for a MIME message to not have any Cc: or Bcc: recipients.

func (*Message) SetDKIM

func (m *Message) SetDKIM(dkim bool)

SetDKIM arranges to send the o:dkim header with the message, and sets its value accordingly. Refer to the Mailgun documentation for more information.

func (*Message) SetDeliveryTime

func (m *Message) SetDeliveryTime(dt time.Time)

SetDeliveryTime schedules the message for transmission at the indicated time. Pass nil to remove any installed schedule. Refer to the Mailgun documentation for more information.

func (*Message) SetHtml

func (m *Message) SetHtml(html string)

If you're sending a message that isn't already MIME encoded, SetHtml() will arrange to bundle an HTML representation of your message in addition to your plain-text body.

func (*Message) SetTracking

func (m *Message) SetTracking(tracking bool)

SetTracking sets the o:tracking message parameter to adjust, on a message-by-message basis, whether or not Mailgun will rewrite URLs to facilitate event tracking. Events tracked includes opens, clicks, unsubscribes, etc. Note: simply calling this method ensures that the o:tracking header is passed in with the message. Its yes/no setting is determined by the call's parameter. Note that this header is not passed on to the final recipient(s). Refer to the Mailgun documentation for more information.

func (*Message) SetTrackingClicks

func (m *Message) SetTrackingClicks(trackingClicks bool)

Refer to the Mailgun documentation for more information.

func (*Message) SetTrackingOpens

func (m *Message) SetTrackingOpens(trackingOpens bool)

Refer to the Mailgun documentation for more information.

type ReaderAttachment

type ReaderAttachment struct {
	Filename   string
	ReadCloser io.ReadCloser
}

type Route

type Route struct {
	Priority    int      `json:"priority,omitempty"`
	Description string   `json:"description,omitempty"`
	Expression  string   `json:"expression,omitempty"`
	Actions     []string `json:"actions,omitempty"`

	CreatedAt string `json:"created_at,omitempty"`
	ID        string `json:"id,omitempty"`
}

A Route structure contains information on a configured or to-be-configured route. The Priority field indicates how soon the route works relative to other configured routes. Routes of equal priority are consulted in chronological order. The Description field provides a human-readable description for the route. Mailgun ignores this field except to provide the description when viewing the Mailgun web control panel. The Expression field lets you specify a pattern to match incoming messages against. The Actions field contains strings specifying what to do with any message which matches the provided expression. The CreatedAt field provides a time-stamp for when the route came into existence. Finally, the ID field provides a unique identifier for this route.

When creating a new route, the SDK only uses a subset of the fields of this structure. In particular, CreatedAt and ID are meaningless in this context, and will be ignored. Only Priority, Description, Expression, and Actions need be provided.

type Stat

type Stat struct {
	Event      string         `json:"event"`
	TotalCount int            `json:"total_count"`
	CreatedAt  string         `json:"created_at"`
	Id         string         `json:"id"`
	Tags       map[string]int `json:"tags"`
}

type StoredAttachment

type StoredAttachment struct {
	Size        int    `json:"size"`
	Url         string `json:"url"`
	Name        string `json:"name"`
	ContentType string `json:"content-type"`
}

StoredAttachment structures contain information on an attachment associated with a stored message.

type StoredMessage

type StoredMessage struct {
	Recipients        string                 `json:"recipients"`
	Sender            string                 `json:"sender"`
	From              string                 `json:"from"`
	Subject           string                 `json:"subject"`
	BodyPlain         string                 `json:"body-plain"`
	StrippedText      string                 `json:"stripped-text"`
	StrippedSignature string                 `json:"stripped-signature"`
	BodyHtml          string                 `json:"body-html"`
	StrippedHtml      string                 `json:"stripped-html"`
	Attachments       []StoredAttachment     `json:"attachments"`
	MessageUrl        string                 `json:"message-url"`
	ContentIDMap      map[string]interface{} `json:"content-id-map"`
	MessageHeaders    [][]string             `json:"message-headers"`
}

StoredMessage structures contain the (parsed) message content for an email sent to a Mailgun account.

The MessageHeaders field is special, in that it's formatted as a slice of pairs. Each pair consists of a name [0] and value [1]. Array notation is used instead of a map because that's how it's sent over the wire, and it's how encoding/json expects this field to be.

type StoredMessageRaw

type StoredMessageRaw struct {
	Recipients string `json:"recipients"`
	Sender     string `json:"sender"`
	From       string `json:"from"`
	Subject    string `json:"subject"`
	BodyMime   string `json:"body-mime"`
}

type UnexpectedResponseError

type UnexpectedResponseError struct {
	Expected []int
	Actual   int
	URL      string
}

This error will be returned whenever a Mailgun API returns an error response. Your application can check the Actual field to see the actual HTTP response code returned. URL contains the base URL accessed, sans any query parameters.

func (*UnexpectedResponseError) Error

func (e *UnexpectedResponseError) Error() string

Error() performs as String().

func (*UnexpectedResponseError) String

func (e *UnexpectedResponseError) String() string

String() converts the error into a human-readable, logfmt-compliant string. See http://godoc.org/github.com/kr/logfmt for details on logfmt formatting.

type Unsubscription

type Unsubscription struct {
	CreatedAt string `json:"created_at"`
	Tag       string `json:"tag"`
	ID        string `json:"id"`
	Address   string `json:"address"`
}

Jump to

Keyboard shortcuts

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