mailgun

package module
v3.6.4 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2020 License: BSD-3-Clause Imports: 28 Imported by: 38

README

Mailgun with Go

GoDoc Build Status

Go library for interacting with the Mailgun API.

NOTE: Backward compatibility has been broken with the v3.0 release which includes versioned paths required by 1.11 go modules (See Releasing Modules). Pin your dependencies to the v1.1.1 or v2.0 tag if you are not ready for v3.0

Usage

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/mailgun/mailgun-go/v3"
)

// Your available domain names can be found here:
// (https://app.mailgun.com/app/domains)
var yourDomain string = "your-domain-name" // e.g. mg.yourcompany.com

// You can find the Private API Key in your Account Menu, under "Settings":
// (https://app.mailgun.com/app/account/security)
var privateAPIKey string = "your-private-key"


func main() {
    // Create an instance of the Mailgun Client
    mg := mailgun.NewMailgun(yourDomain, privateAPIKey)

    sender := "sender@example.com"
    subject := "Fancy subject!"
    body := "Hello from Mailgun Go!"
    recipient := "recipient@example.com"

    // The message object allows you to add attachments and Bcc recipients
    message := mg.NewMessage(sender, subject, body, recipient)

    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    defer cancel()

    // Send the message	with a 10 second timeout
    resp, id, err := mg.Send(ctx, message)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("ID: %s Resp: %s\n", id, resp)
}

Get Events

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/mailgun/mailgun-go/v3"
    "github.com/mailgun/mailgun-go/v3/events"
)

func main() {
    // You can find the Private API Key in your Account Menu, under "Settings":
    // (https://app.mailgun.com/app/account/security)
    mg := mailgun.NewMailgun("your-domain.com", "your-private-key")

	it := mg.ListEvents(&mailgun.ListEventOptions{Limit: 100})

	var page []mailgun.Event

	// The entire operation should not take longer than 30 seconds
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
	defer cancel()

	// For each page of 100 events
	for it.Next(ctx, &page) {
		for _, e := range page {
			// You can access some fields via the interface
			fmt.Printf("Event: '%s' TimeStamp: '%s'\n", e.GetName(), e.GetTimestamp())

			// and you can act upon each event by type
			switch event := e.(type) {
			case *events.Accepted:
				fmt.Printf("Accepted: auth: %t\n", event.Flags.IsAuthenticated)
			case *events.Delivered:
				fmt.Printf("Delivered transport: %s\n", event.Envelope.Transport)
			case *events.Failed:
				fmt.Printf("Failed reason: %s\n", event.Reason)
			case *events.Clicked:
				fmt.Printf("Clicked GeoLocation: %s\n", event.GeoLocation.Country)
			case *events.Opened:
				fmt.Printf("Opened GeoLocation: %s\n", event.GeoLocation.Country)
			case *events.Rejected:
				fmt.Printf("Rejected reason: %s\n", event.Reject.Reason)
			case *events.Stored:
				fmt.Printf("Stored URL: %s\n", event.Storage.URL)
			case *events.Unsubscribed:
				fmt.Printf("Unsubscribed client OS: %s\n", event.ClientInfo.ClientOS)
			}
		}
	}
}

Event Polling

The mailgun library has built-in support for polling the events api

package main

import (
    "context"
    "time"

    "github.com/mailgun/mailgun-go/v3"
)

func main() {
    // You can find the Private API Key in your Account Menu, under "Settings":
    // (https://app.mailgun.com/app/account/security)
    mg := mailgun.NewMailgun("your-domain.com", "your-private-key")

	begin := time.Now().Add(time.Second * -3)

	// Very short poll interval
	it := mg.PollEvents(&mailgun.ListEventOptions{
		// Only events with a timestamp after this date/time will be returned
		Begin: &begin,
		// How often we poll the api for new events
		PollInterval: time.Second * 30,
	})

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

    // Poll until our email event arrives
    var page []mailgun.Event
    for it.Poll(ctx, &page) {
        for _, e := range page {
            // Do something with event
        }
    }
}

Email Validations

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/mailgun/mailgun-go/v3"
)

// If your plan does not include email validations but you have an account,
// use your Public Validation api key. If your plan does include email validations,
// use your Private API key. You can find both the Private and
// Public Validation API Keys in your Account Menu, under "Settings":
// (https://app.mailgun.com/app/account/security)
var apiKey string = "your-api-key"

func main() {
    // Create an instance of the Validator
    v := mailgun.NewEmailValidator(apiKey)

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

    email, err := v.ValidateEmail(ctx, "recipient@example.com", false)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Valid: %t\n", email.IsValid)
}

Webhook Handling

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "os"
    "time"

    "github.com/mailgun/mailgun-go/v3"
    "github.com/mailgun/mailgun-go/v3/events"
)

func main() {

    // You can find the Private API Key in your Account Menu, under "Settings":
    // (https://app.mailgun.com/app/account/security)
    mg := mailgun.NewMailgun("your-domain.com", "private-api-key")

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

		var payload mailgun.WebhookPayload
		if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
			fmt.Printf("decode JSON error: %s", err)
			w.WriteHeader(http.StatusNotAcceptable)
			return
		}

		verified, err := mg.VerifyWebhookSignature(payload.Signature)
		if err != nil {
			fmt.Printf("verify error: %s\n", err)
			w.WriteHeader(http.StatusNotAcceptable)
			return
		}

		if !verified {
			w.WriteHeader(http.StatusNotAcceptable)
			fmt.Printf("failed verification %+v\n", payload.Signature)
			return
		}

		fmt.Printf("Verified Signature\n")

		// Parse the event provided by the webhook payload
		e, err := mailgun.ParseEvent(payload.EventData)
		if err != nil {
			fmt.Printf("parse event error: %s\n", err)
			return
		}

		switch event := e.(type) {
		case *events.Accepted:
			fmt.Printf("Accepted: auth: %t\n", event.Flags.IsAuthenticated)
		case *events.Delivered:
			fmt.Printf("Delivered transport: %s\n", event.Envelope.Transport)
		}
	})

	fmt.Println("Serve on :9090...")
	if err := http.ListenAndServe(":9090", nil); err != nil {
		fmt.Printf("serve error: %s\n", err)
		os.Exit(1)
	}
}

Using Templates

Templates enable you to create message templates on your Mailgun account and then populate the data variables at send-time. This allows you to have your layout and design managed on the server and handle the data on the client. The template variables are added as a JSON stringified X-Mailgun-Variables header. For example, if you have a template to send a password reset link, you could do the following:

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/mailgun/mailgun-go/v3"
)

// Your available domain names can be found here:
// (https://app.mailgun.com/app/domains)
var yourDomain string = "your-domain-name" // e.g. mg.yourcompany.com

// You can find the Private API Key in your Account Menu, under "Settings":
// (https://app.mailgun.com/app/account/security)
var privateAPIKey string = "your-private-key"


func main() {
    // Create an instance of the Mailgun Client
    mg := mailgun.NewMailgun(yourDomain, privateAPIKey)

    sender := "sender@example.com"
    subject := "Fancy subject!"
    body := ""
    recipient := "recipient@example.com"

    // The message object allows you to add attachments and Bcc recipients
		message := mg.NewMessage(sender, subject, body, recipient)
		message.SetTemplate("passwordReset")
		message.AddTemplateVariable("passwordResetLink", "some link to your site unique to your user")

    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    defer cancel()

    // Send the message	with a 10 second timeout
    resp, id, err := mg.Send(ctx, message)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("ID: %s Resp: %s\n", id, resp)
}

The official mailgun documentation includes examples using this library. Go here and click on the "Go" button at the top of the page.

EU Region

European customers will need to change the default API Base to access your domains

mg := mailgun.NewMailgun("your-domain.com", "private-api-key")
mg.SetAPIBase(mailgun.APIBaseEU)

Installation

If you are using golang modules make sure you include the /v3 at the end of your import paths

$ go get github.com/mailgun/mailgun-go/v3

If you are not using golang modules, you can drop the /v3 at the end of the import path. As long as you are using the latest 1.10 or 1.11 golang release, import paths that end in /v3 in your code should work fine even if you do not have golang modules enabled for your project.

$ go get github.com/mailgun/mailgun-go

NOTE for go dep users

Using version 3 of the mailgun-go library with go dep currently results in the following error

"github.com/mailgun/mailgun-go/v3/events", which contains malformed code: no package exists at ...

This is a known bug in go dep. You can follow the PR to fix this bug here Until this bug is fixed, the best way to use version 3 of the mailgun-go library is to use the golang community supported golang modules.

Testing

WARNING - running the tests will cost you money!

To run the tests various environment variables must be set. These are:

  • MG_DOMAIN is the domain name - this is a value registered in the Mailgun admin interface.
  • MG_PUBLIC_API_KEY is the Public Validation API key - you can get this value from the Mailgun security page
  • MG_API_KEY is the Private API key - you can get this value from the Mailgun security page
  • MG_EMAIL_TO is the email address used in various sending tests.

and finally

  • MG_SPEND_MONEY if this value is set the part of the test that use the API to actually send email will be run - be aware this will count on your quota and this will cost you money.

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

Documentation

Overview

Package mailgun 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>
                 Derrick J. Wippler <thrawn01 %at% gmail.com>

Examples

All functions and method have a corresponding test, so if you don't find an example for a function you'd like to know more about, please check 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.

List iterators

Most methods that begin with `List` return an iterator which simplfies paging through large result sets returned by the mailgun API. Most `List` methods allow you to specify a `Limit` parameter which as you'd expect, limits the number of items returned per page. Note that, at present, Mailgun imposes its own cap of 100 items per page, for all API endpoints.

For example, the following iterates over all pages of events 100 items at a time

mg := mailgun.NewMailgun("your-domain.com", "your-api-key")
it := mg.ListEvents(&mailgun.ListEventOptions{Limit: 100})

// The entire operation should not take longer than 30 seconds
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()

// For each page of 100 events
var page []mailgun.Event
for it.Next(ctx, &page) {
  for _, e := range page {
    // Do something with 'e'
  }
}

License

Copyright (c) 2013-2019, 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 (
	// Tag the received message with headers providing a measure of its spamness.
	SpamActionTag = SpamAction("tag")
	// Prevents Mailgun from taking any action on what it perceives to be spam.
	SpamActionDisabled = SpamAction("disabled")
	// instructs Mailgun to just block or delete the message all-together.
	SpamActionDelete = SpamAction("delete")
)

Use these to specify a spam action when creating a new domain.

View Source
const (
	// Base Url the library uses to contact mailgun. Use SetAPIBase() to override
	APIBase   = "https://api.mailgun.net/v3"
	APIBaseUS = APIBase
	APIBaseEU = "https://api.eu.mailgun.net/v3"
)
View Source
const (
	// ReadOnly specifies that nobody, including Members, may send messages to
	// the mailing list.  Messages distributed on such lists come from list
	// administrator accounts only.
	AccessLevelReadOnly = "readonly"
	// Members specifies that only those who subscribe to the mailing list may
	// send messages.
	AccessLevelMembers = "members"
	// Everyone specifies that anyone and everyone may both read and submit
	// messages to the mailing list, including non-subscribers.
	AccessLevelEveryone = "everyone"
)

A mailing list may have one of three membership modes.

View Source
const (
	ResolutionHour  = Resolution("hour")
	ResolutionDay   = Resolution("day")
	ResolutionMonth = Resolution("month")
)

Indicate which resolution a stat response for request is for

View Source
const (
	TemplateEngineMustache   = TemplateEngine("mustache")
	TemplateEngineHandlebars = TemplateEngine("handlebars")
	TemplateEngineGo         = TemplateEngine("go")
)

Used by CreateTemplate() and AddTemplateVersion() to specify the template engine

View Source
const MailgunGoUserAgent = "mailgun-go/" + Version

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.

View Source
const MaxNumberOfTags = 3

MaxNumberOfTags represents the maximum number of tags that can be added for a message

View Source
const Version = "3.6.1"

Version of current release

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 Debug = false

Set true to write the HTTP requests in curl for to stdout

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

Returned when a required parameter is missing.

View Source
var ErrInvalidMessage = errors.New("message not valid")

ErrInvalidMessage is returned by `Send()` when the `mailgun.Message` struct is incomplete

View Source
var EventNames = map[string]func() Event{
	"accepted":                 new_(events.Accepted{}),
	"clicked":                  new_(events.Clicked{}),
	"complained":               new_(events.Complained{}),
	"delivered":                new_(events.Delivered{}),
	"failed":                   new_(events.Failed{}),
	"opened":                   new_(events.Opened{}),
	"rejected":                 new_(events.Rejected{}),
	"stored":                   new_(events.Stored{}),
	"unsubscribed":             new_(events.Unsubscribed{}),
	"list_member_uploaded":     new_(events.ListMemberUploaded{}),
	"list_member_upload_error": new_(events.ListMemberUploadError{}),
	"list_uploaded":            new_(events.ListUploaded{}),
}

A list of all JSON event types returned by the /events API

Functions

func GetStatusFromErr

func GetStatusFromErr(err error) int

Extract the http status code from error object

func TimeToFloat

func TimeToFloat(t time.Time) float64

Given time.Time{} return a float64 as given in mailgun event timestamps

Types

type Accepted

type Accepted struct {
	Incoming int `json:"incoming"`
	Outgoing int `json:"outgoing"`
	Total    int `json:"total"`
}

Stats on accepted messages

type AccessLevel

type AccessLevel string

Specify the access of a mailing list member

type Bounce

type Bounce struct {
	// The time at which Mailgun detected the bounce.
	CreatedAt RFC2822Time `json:"created_at"`
	// Code provides the SMTP error code that caused the bounce
	Code string `json:"code"`
	// Address the bounce is for
	Address string `json:"address"`
	// human readable reason why
	Error string `json:"error"`
}

Bounce aggregates data relating to undeliverable messages to a specific intended recipient, identified by Address.

type BouncesIterator

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

func (*BouncesIterator) Err

func (ci *BouncesIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*BouncesIterator) First

func (ci *BouncesIterator) First(ctx context.Context, items *[]Bounce) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*BouncesIterator) Last

func (ci *BouncesIterator) Last(ctx context.Context, items *[]Bounce) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*BouncesIterator) Next

func (ci *BouncesIterator) Next(ctx context.Context, items *[]Bounce) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*BouncesIterator) Previous

func (ci *BouncesIterator) Previous(ctx context.Context, items *[]Bounce) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type BufferAttachment

type BufferAttachment struct {
	Filename string
	Buffer   []byte
}

type Complaint

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

Complaint structures track how many times one of your emails have been marked as spam. the recipient thought your messages were not solicited.

type ComplaintsIterator

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

func (*ComplaintsIterator) Err

func (ci *ComplaintsIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*ComplaintsIterator) First

func (ci *ComplaintsIterator) First(ctx context.Context, items *[]Complaint) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*ComplaintsIterator) Last

func (ci *ComplaintsIterator) Last(ctx context.Context, items *[]Complaint) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*ComplaintsIterator) Next

func (ci *ComplaintsIterator) Next(ctx context.Context, items *[]Complaint) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*ComplaintsIterator) Previous

func (ci *ComplaintsIterator) Previous(ctx context.Context, items *[]Complaint) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type CreateDomainOptions

type CreateDomainOptions struct {
	Password           string
	SpamAction         SpamAction
	Wildcard           bool
	ForceDKIMAuthority bool
	DKIMKeySize        int
	IPS                []string
}

Optional parameters when creating a domain

type Credential

type Credential struct {
	CreatedAt RFC2822Time `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 CredentialsIterator

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

func (*CredentialsIterator) Err

func (ri *CredentialsIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*CredentialsIterator) First

func (ri *CredentialsIterator) First(ctx context.Context, items *[]Credential) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*CredentialsIterator) Last

func (ri *CredentialsIterator) Last(ctx context.Context, items *[]Credential) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*CredentialsIterator) Next

func (ri *CredentialsIterator) Next(ctx context.Context, items *[]Credential) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*CredentialsIterator) Offset

func (ri *CredentialsIterator) Offset() int

Offset returns the current offset of the iterator

func (*CredentialsIterator) Previous

func (ri *CredentialsIterator) Previous(ctx context.Context, items *[]Credential) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

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 Delivered

type Delivered struct {
	Smtp  int `json:"smtp"`
	Http  int `json:"http"`
	Total int `json:"total"`
}

Stats on delivered messages

type Domain

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

A Domain structure holds information about a domain used when sending mail.

type DomainConnection

type DomainConnection struct {
	RequireTLS       bool `json:"require_tls"`
	SkipVerification bool `json:"skip_verification"`
}

Specify the domain connection options

type DomainResponse added in v3.3.0

type DomainResponse struct {
	Domain              Domain      `json:"domain"`
	ReceivingDNSRecords []DNSRecord `json:"receiving_dns_records"`
	SendingDNSRecords   []DNSRecord `json:"sending_dns_records"`
}

type DomainTracking

type DomainTracking struct {
	Click       TrackingStatus `json:"click"`
	Open        TrackingStatus `json:"open"`
	Unsubscribe TrackingStatus `json:"unsubscribe"`
}

Specify the domain tracking options

type DomainsIterator

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

func (*DomainsIterator) Err

func (ri *DomainsIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*DomainsIterator) First

func (ri *DomainsIterator) First(ctx context.Context, items *[]Domain) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*DomainsIterator) Last

func (ri *DomainsIterator) Last(ctx context.Context, items *[]Domain) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*DomainsIterator) Next

func (ri *DomainsIterator) Next(ctx context.Context, items *[]Domain) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*DomainsIterator) Offset

func (ri *DomainsIterator) Offset() int

Offset returns the current offset of the iterator

func (*DomainsIterator) Previous

func (ri *DomainsIterator) Previous(ctx context.Context, items *[]Domain) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type EmailValidator

type EmailValidator interface {
	ValidateEmail(ctx context.Context, email string, mailBoxVerify bool) (EmailVerification, error)
	ParseAddresses(ctx context.Context, addresses ...string) ([]string, []string, error)
}

type EmailValidatorImpl

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

func NewEmailValidator

func NewEmailValidator(apiKey string) *EmailValidatorImpl

Creates a new validation instance. * If a public key is provided, uses the public validation endpoints * If a private key is provided, uses the private validation endpoints

func NewEmailValidatorFromEnv

func NewEmailValidatorFromEnv() (*EmailValidatorImpl, error)

NewEmailValidatorFromEnv returns a new EmailValidator using environment variables If MG_PUBLIC_API_KEY is set, assume using the free validation subject to daily usage limits If only MG_API_KEY is set, assume using the /private validation routes with no daily usage limits

func (*EmailValidatorImpl) APIBase

func (m *EmailValidatorImpl) APIBase() string

APIBase returns the API Base URL configured for this client.

func (*EmailValidatorImpl) APIKey

func (m *EmailValidatorImpl) APIKey() string

APIKey returns the API key used for validations

func (*EmailValidatorImpl) Client

func (m *EmailValidatorImpl) Client() *http.Client

Client returns the HTTP client configured for this client.

func (*EmailValidatorImpl) ParseAddresses

func (m *EmailValidatorImpl) ParseAddresses(ctx context.Context, 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.

func (*EmailValidatorImpl) SetAPIBase

func (m *EmailValidatorImpl) SetAPIBase(address string)

SetAPIBase updates the API Base URL for this client.

func (*EmailValidatorImpl) SetClient

func (m *EmailValidatorImpl) SetClient(c *http.Client)

SetClient updates the HTTP client for this client.

func (*EmailValidatorImpl) ValidateEmail

func (m *EmailValidatorImpl) ValidateEmail(ctx context.Context, email string, mailBoxVerify bool) (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.)

type EmailVerification

type EmailVerification struct {
	// Indicates whether an email address conforms to IETF RFC standards.
	IsValid bool `json:"is_valid"`
	// Indicates whether an email address is deliverable.
	MailboxVerification string `json:"mailbox_verification"`
	// Parts records the different subfields of the parsed email address
	Parts EmailVerificationParts `json:"parts"`
	// Echoes the address provided.
	Address string `json:"address"`
	// Provides a simple recommendation in case the address is invalid or
	// Mailgun thinks you might have a typo. May be empty, in which case
	// Mailgun has no recommendation to give.
	DidYouMean string `json:"did_you_mean"`
	// Indicates whether Mailgun thinks the address is from a known
	// disposable mailbox provider.
	IsDisposableAddress bool `json:"is_disposable_address"`
	// Indicates whether Mailgun thinks the address is an email distribution list.
	IsRoleAddress bool `json:"is_role_address"`
	// A human readable reason the address is reported as invalid
	Reason string `json:"reason"`
}

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

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 interface {
	easyjson.Unmarshaler
	easyjson.Marshaler
	GetName() string
	SetName(name string)
	GetTimestamp() time.Time
	SetTimestamp(time.Time)
	GetID() string
	SetID(id string)
}

All events returned by the EventIterator conform to this interface

func ParseEvent added in v3.2.0

func ParseEvent(raw []byte) (Event, error)

Parse converts raw bytes data into an event struct. Can accept events.RawJSON as input

func ParseEvents added in v3.2.0

func ParseEvents(raw []events.RawJSON) ([]Event, error)

Given a slice of events.RawJSON events return a slice of Event for each parsed event

type EventIterator

type EventIterator struct {
	events.Response
	// contains filtered or unexported fields
}

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

func (*EventIterator) Err

func (ei *EventIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*EventIterator) First

func (ei *EventIterator) First(ctx context.Context, events *[]Event) bool

First retrieves the first page of events from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*EventIterator) Last

func (ei *EventIterator) Last(ctx context.Context, events *[]Event) bool

Last retrieves the last page of events from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*EventIterator) Next

func (ei *EventIterator) Next(ctx context.Context, events *[]Event) bool

Next retrieves the next page of events from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*EventIterator) Previous

func (ei *EventIterator) Previous(ctx context.Context, events *[]Event) bool

Previous retrieves the previous page of events from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type EventPoller

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

EventPoller maintains the state necessary for polling events

func (*EventPoller) Err

func (ep *EventPoller) Err() error

If an error occurred during polling `Err()` will return non nil

func (*EventPoller) Poll

func (ep *EventPoller) Poll(ctx context.Context, events *[]Event) bool

type Export

type Export struct {
	ID     string `json:"id"`
	Status string `json:"status"`
	URL    string `json:"url"`
}

type ExportList

type ExportList struct {
	Items []Export `json:"items"`
}

type Failed

type Failed struct {
	Temporary Temporary `json:"temporary"`
	Permanent Permanent `json:"permanent"`
}

Stats on failed messages

type GetStatOptions

type GetStatOptions struct {
	Resolution Resolution
	Duration   string
	Start      time.Time
	End        time.Time
}

Options for GetStats()

type IPAddress

type IPAddress struct {
	IP        string `json:"ip"`
	RDNS      string `json:"rdns"`
	Dedicated bool   `json:"dedicated"`
}

type ListEventOptions

type ListEventOptions struct {
	// Limits the results to a specific start and end time
	Begin, End time.Time
	// 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.
	ForceAscending, ForceDescending bool
	// Compact, if true, compacts the returned JSON to minimize transmission bandwidth.
	Compact bool
	// Limit caps the number of results returned.  If left unspecified, MailGun assumes 100.
	Limit int
	// Filter allows the caller to provide more specialized filters on the query.
	// Consult the Mailgun documentation for more details.
	Filter       map[string]string
	PollInterval time.Duration
}

ListEventOptions{} modifies the behavior of ListEvents()

type ListOptions

type ListOptions struct {
	Limit int
}

Used by List methods to specify what list parameters to send to the mailgun API

type ListTagOptions

type ListTagOptions struct {
	// Restrict the page size to this limit
	Limit int
	// Return only the tags starting with the given prefix
	Prefix string
}

type ListTemplateOptions added in v3.4.0

type ListTemplateOptions struct {
	Limit  int
	Active bool
}

type ListsIterator

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

func (*ListsIterator) Err

func (li *ListsIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*ListsIterator) First

func (li *ListsIterator) First(ctx context.Context, items *[]MailingList) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*ListsIterator) Last

func (li *ListsIterator) Last(ctx context.Context, items *[]MailingList) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*ListsIterator) Next

func (li *ListsIterator) Next(ctx context.Context, items *[]MailingList) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*ListsIterator) Previous

func (li *ListsIterator) Previous(ctx context.Context, items *[]MailingList) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type Mailgun

type Mailgun interface {
	APIBase() string
	Domain() string
	APIKey() string
	Client() *http.Client
	SetClient(client *http.Client)
	SetAPIBase(url string)

	Send(ctx context.Context, m *Message) (string, string, error)
	ReSend(ctx context.Context, id string, recipients ...string) (string, string, error)
	NewMessage(from, subject, text string, to ...string) *Message
	NewMIMEMessage(body io.ReadCloser, to ...string) *Message

	ListBounces(opts *ListOptions) *BouncesIterator
	GetBounce(ctx context.Context, address string) (Bounce, error)
	AddBounce(ctx context.Context, address, code, err string) error
	DeleteBounce(ctx context.Context, address string) error

	GetStats(ctx context.Context, events []string, opts *GetStatOptions) ([]Stats, error)
	GetTag(ctx context.Context, tag string) (Tag, error)
	DeleteTag(ctx context.Context, tag string) error
	ListTags(*ListTagOptions) *TagIterator

	ListDomains(opts *ListOptions) *DomainsIterator
	GetDomain(ctx context.Context, domain string) (DomainResponse, error)
	CreateDomain(ctx context.Context, name string, opts *CreateDomainOptions) (DomainResponse, error)
	DeleteDomain(ctx context.Context, name string) error
	VerifyDomain(ctx context.Context, name string) (string, error)
	UpdateDomainConnection(ctx context.Context, domain string, dc DomainConnection) error
	GetDomainConnection(ctx context.Context, domain string) (DomainConnection, error)
	GetDomainTracking(ctx context.Context, domain string) (DomainTracking, error)
	UpdateClickTracking(ctx context.Context, domain, active string) error
	UpdateUnsubscribeTracking(ctx context.Context, domain, active, htmlFooter, textFooter string) error
	UpdateOpenTracking(ctx context.Context, domain, active string) error

	GetStoredMessage(ctx context.Context, url string) (StoredMessage, error)
	GetStoredMessageRaw(ctx context.Context, id string) (StoredMessageRaw, error)
	GetStoredAttachment(ctx context.Context, url string) ([]byte, error)

	// Deprecated
	GetStoredMessageForURL(ctx context.Context, url string) (StoredMessage, error)
	// Deprecated
	GetStoredMessageRawForURL(ctx context.Context, url string) (StoredMessageRaw, error)

	ListCredentials(opts *ListOptions) *CredentialsIterator
	CreateCredential(ctx context.Context, login, password string) error
	ChangeCredentialPassword(ctx context.Context, login, password string) error
	DeleteCredential(ctx context.Context, login string) error

	ListUnsubscribes(opts *ListOptions) *UnsubscribesIterator
	GetUnsubscribe(ctx context.Context, address string) (Unsubscribe, error)
	CreateUnsubscribe(ctx context.Context, address, tag string) error
	DeleteUnsubscribe(ctx context.Context, address string) error
	DeleteUnsubscribeWithTag(ctx context.Context, a, t string) error

	ListComplaints(opts *ListOptions) *ComplaintsIterator
	GetComplaint(ctx context.Context, address string) (Complaint, error)
	CreateComplaint(ctx context.Context, address string) error
	DeleteComplaint(ctx context.Context, address string) error

	ListRoutes(opts *ListOptions) *RoutesIterator
	GetRoute(ctx context.Context, address string) (Route, error)
	CreateRoute(ctx context.Context, address Route) (Route, error)
	DeleteRoute(ctx context.Context, address string) error
	UpdateRoute(ctx context.Context, address string, r Route) (Route, error)

	ListWebhooks(ctx context.Context) (map[string][]string, error)
	CreateWebhook(ctx context.Context, kind string, url []string) error
	DeleteWebhook(ctx context.Context, kind string) error
	GetWebhook(ctx context.Context, kind string) ([]string, error)
	UpdateWebhook(ctx context.Context, kind string, url []string) error
	VerifyWebhookRequest(req *http.Request) (verified bool, err error)
	VerifyWebhookSignature(sig Signature) (verified bool, err error)

	ListMailingLists(opts *ListOptions) *ListsIterator
	CreateMailingList(ctx context.Context, address MailingList) (MailingList, error)
	DeleteMailingList(ctx context.Context, address string) error
	GetMailingList(ctx context.Context, address string) (MailingList, error)
	UpdateMailingList(ctx context.Context, address string, ml MailingList) (MailingList, error)

	ListMembers(address string, opts *ListOptions) *MemberListIterator
	GetMember(ctx context.Context, MemberAddr, listAddr string) (Member, error)
	CreateMember(ctx context.Context, merge bool, addr string, prototype Member) error
	CreateMemberList(ctx context.Context, subscribed *bool, addr string, newMembers []interface{}) error
	UpdateMember(ctx context.Context, Member, list string, prototype Member) (Member, error)
	DeleteMember(ctx context.Context, Member, list string) error

	ListEvents(*ListEventOptions) *EventIterator
	PollEvents(*ListEventOptions) *EventPoller

	ListIPS(ctx context.Context, dedicated bool) ([]IPAddress, error)
	GetIP(ctx context.Context, ip string) (IPAddress, error)
	ListDomainIPS(ctx context.Context) ([]IPAddress, error)
	AddDomainIP(ctx context.Context, ip string) error
	DeleteDomainIP(ctx context.Context, ip string) error

	ListExports(ctx context.Context, url string) ([]Export, error)
	GetExport(ctx context.Context, id string) (Export, error)
	GetExportLink(ctx context.Context, id string) (string, error)
	CreateExport(ctx context.Context, url string) error

	GetTagLimits(ctx context.Context, domain string) (TagLimits, error)

	CreateTemplate(ctx context.Context, template *Template) error
	GetTemplate(ctx context.Context, name string) (Template, error)
	UpdateTemplate(ctx context.Context, template *Template) error
	DeleteTemplate(ctx context.Context, name string) error
	ListTemplates(opts *ListTemplateOptions) *TemplatesIterator

	AddTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error
	GetTemplateVersion(ctx context.Context, templateName, tag string) (TemplateVersion, error)
	UpdateTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error
	DeleteTemplateVersion(ctx context.Context, templateName, tag string) error
	ListTemplateVersions(templateName string, opts *ListOptions) *TemplateVersionsIterator
}

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.

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 NewMailgun

func NewMailgun(domain, apiKey string) *MailgunImpl

NewMailGun creates a new client instance.

func NewMailgunFromEnv

func NewMailgunFromEnv() (*MailgunImpl, error)

NewMailgunFromEnv returns a new Mailgun client using the environment variables MG_API_KEY, MG_DOMAIN, and MG_URL

func (*MailgunImpl) APIBase

func (mg *MailgunImpl) APIBase() string

APIBase returns the API Base URL configured for this client.

func (*MailgunImpl) APIKey

func (mg *MailgunImpl) APIKey() string

ApiKey returns the API key configured for this client.

func (*MailgunImpl) AddBounce

func (mg *MailgunImpl) AddBounce(ctx context.Context, 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) AddDomainIP

func (mg *MailgunImpl) AddDomainIP(ctx context.Context, ip string) error

Assign a dedicated IP to the domain specified.

func (*MailgunImpl) AddTemplateVersion

func (mg *MailgunImpl) AddTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error

AddTemplateVersion adds a template version to a template

func (*MailgunImpl) ChangeCredentialPassword

func (mg *MailgunImpl) ChangeCredentialPassword(ctx context.Context, login, password string) error

ChangeCredentialPassword attempts to alter the indicated credential's password.

func (*MailgunImpl) Client

func (mg *MailgunImpl) Client() *http.Client

Client returns the HTTP client configured for this client.

func (*MailgunImpl) CreateComplaint

func (mg *MailgunImpl) CreateComplaint(ctx context.Context, 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(ctx context.Context, login, password string) error

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

func (*MailgunImpl) CreateDomain

func (mg *MailgunImpl) CreateDomain(ctx context.Context, name string, opts *CreateDomainOptions) (DomainResponse, 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) CreateExport

func (mg *MailgunImpl) CreateExport(ctx context.Context, url string) error

Create an export based on the URL given

func (*MailgunImpl) CreateMailingList

func (mg *MailgunImpl) CreateMailingList(ctx context.Context, prototype MailingList) (MailingList, error)

CreateMailingList 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(ctx context.Context, 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(ctx context.Context, u *bool, addr string, newMembers []interface{}) error

CreateMemberList registers multiple Members and non-Member members to a single mailing list in a single round-trip. u indicates if the existing members should be updated or duplicates should be updated. 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(ctx context.Context, prototype Route) (_ignored Route, err 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) CreateTemplate

func (mg *MailgunImpl) CreateTemplate(ctx context.Context, template *Template) error

Create a new template which can be used to attach template versions to

func (*MailgunImpl) CreateUnsubscribe

func (mg *MailgunImpl) CreateUnsubscribe(ctx context.Context, address, tag string) error

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

func (*MailgunImpl) CreateWebhook

func (mg *MailgunImpl) CreateWebhook(ctx context.Context, kind string, urls []string) error

CreateWebhook installs a new webhook for your domain.

func (*MailgunImpl) DeleteBounce

func (mg *MailgunImpl) DeleteBounce(ctx context.Context, address string) error

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

func (*MailgunImpl) DeleteComplaint

func (mg *MailgunImpl) DeleteComplaint(ctx context.Context, 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(ctx context.Context, login string) error

DeleteCredential attempts to remove the indicated principle from the domain.

func (*MailgunImpl) DeleteDomain

func (mg *MailgunImpl) DeleteDomain(ctx context.Context, name string) error

DeleteDomain instructs Mailgun to dispose of the named domain name

func (*MailgunImpl) DeleteDomainIP

func (mg *MailgunImpl) DeleteDomainIP(ctx context.Context, ip string) error

Unassign an IP from the domain specified.

func (*MailgunImpl) DeleteMailingList

func (mg *MailgunImpl) DeleteMailingList(ctx context.Context, addr string) error

DeleteMailingList 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(ctx context.Context, member, addr string) error

DeleteMember removes the member from the list.

func (*MailgunImpl) DeleteRoute

func (mg *MailgunImpl) DeleteRoute(ctx context.Context, 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) DeleteTag

func (mg *MailgunImpl) DeleteTag(ctx context.Context, tag string) error

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

func (*MailgunImpl) DeleteTemplate

func (mg *MailgunImpl) DeleteTemplate(ctx context.Context, name string) error

Delete a template given a template name

func (*MailgunImpl) DeleteTemplateVersion

func (mg *MailgunImpl) DeleteTemplateVersion(ctx context.Context, templateName, tag string) error

Delete a specific version of a template

func (*MailgunImpl) DeleteUnsubscribe

func (mg *MailgunImpl) DeleteUnsubscribe(ctx context.Context, address string) error

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

func (*MailgunImpl) DeleteUnsubscribeWithTag

func (mg *MailgunImpl) DeleteUnsubscribeWithTag(ctx context.Context, a, t string) error

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

func (*MailgunImpl) DeleteWebhook

func (mg *MailgunImpl) DeleteWebhook(ctx context.Context, kind string) error

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

func (*MailgunImpl) Domain

func (mg *MailgunImpl) Domain() string

Domain returns the domain configured for this client.

func (*MailgunImpl) GetBounce

func (mg *MailgunImpl) GetBounce(ctx context.Context, address string) (Bounce, error)

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

func (*MailgunImpl) GetComplaint

func (mg *MailgunImpl) GetComplaint(ctx context.Context, address string) (Complaint, error)

GetComplaint 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) GetDomain

func (mg *MailgunImpl) GetDomain(ctx context.Context, domain string) (DomainResponse, error)

GetDomain retrieves detailed information about the named domain.

func (*MailgunImpl) GetDomainConnection

func (mg *MailgunImpl) GetDomainConnection(ctx context.Context, domain string) (DomainConnection, error)

GetDomainConnection returns delivery connection settings for the defined domain

func (*MailgunImpl) GetDomainTracking

func (mg *MailgunImpl) GetDomainTracking(ctx context.Context, domain string) (DomainTracking, error)

GetDomainTracking returns tracking settings for a domain

func (*MailgunImpl) GetExport

func (mg *MailgunImpl) GetExport(ctx context.Context, id string) (Export, error)

GetExport gets an export by id

func (mg *MailgunImpl) GetExportLink(ctx context.Context, id string) (string, error)

Download an export by ID. This will respond with a '302 Moved' with the Location header of temporary S3 URL if it is available.

func (*MailgunImpl) GetIP

func (mg *MailgunImpl) GetIP(ctx context.Context, ip string) (IPAddress, error)

GetIP returns information about the specified IP

func (*MailgunImpl) GetMailingList

func (mg *MailgunImpl) GetMailingList(ctx context.Context, addr string) (MailingList, error)

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

func (*MailgunImpl) GetMember

func (mg *MailgunImpl) GetMember(ctx context.Context, s, l string) (Member, error)

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

func (*MailgunImpl) GetRoute

func (mg *MailgunImpl) GetRoute(ctx context.Context, id string) (Route, error)

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

func (*MailgunImpl) GetStats

func (mg *MailgunImpl) GetStats(ctx context.Context, events []string, opts *GetStatOptions) ([]Stats, error)

GetStats returns total stats for a given domain for the specified time period

func (*MailgunImpl) GetStoredAttachment added in v3.3.1

func (mg *MailgunImpl) GetStoredAttachment(ctx context.Context, url string) ([]byte, error)

GetStoredAttachment retrieves the raw MIME body of a received e-mail message attachment.

func (*MailgunImpl) GetStoredMessage

func (mg *MailgunImpl) GetStoredMessage(ctx context.Context, url 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) GetStoredMessageForURL deprecated

func (mg *MailgunImpl) GetStoredMessageForURL(ctx context.Context, url string) (StoredMessage, error)

Deprecated: Use GetStoreMessage() instead

func (*MailgunImpl) GetStoredMessageRaw

func (mg *MailgunImpl) GetStoredMessageRaw(ctx context.Context, url 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) GetStoredMessageRawForURL deprecated

func (mg *MailgunImpl) GetStoredMessageRawForURL(ctx context.Context, url string) (StoredMessageRaw, error)

Deprecated: Use GetStoreMessageRaw() instead

func (*MailgunImpl) GetTag

func (mg *MailgunImpl) GetTag(ctx context.Context, tag string) (Tag, error)

GetTag retrieves metadata about the tag from the api

func (*MailgunImpl) GetTagLimits

func (mg *MailgunImpl) GetTagLimits(ctx context.Context, domain string) (TagLimits, error)

GetTagLimits returns tracking settings for a domain

func (*MailgunImpl) GetTemplate

func (mg *MailgunImpl) GetTemplate(ctx context.Context, name string) (Template, error)

GetTemplate gets a template given the template name

func (*MailgunImpl) GetTemplateVersion

func (mg *MailgunImpl) GetTemplateVersion(ctx context.Context, templateName, tag string) (TemplateVersion, error)

GetTemplateVersion gets a specific version of a template

func (*MailgunImpl) GetUnsubscribe

func (mg *MailgunImpl) GetUnsubscribe(ctx context.Context, address string) (Unsubscribe, error)

Retreives a single unsubscribe record. Can be used to check if a given address is present in the list of unsubscribed users.

func (*MailgunImpl) GetWebhook

func (mg *MailgunImpl) GetWebhook(ctx context.Context, kind string) ([]string, error)

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

func (*MailgunImpl) ListBounces

func (mg *MailgunImpl) ListBounces(opts *ListOptions) *BouncesIterator

ListBounces 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) ListComplaints

func (mg *MailgunImpl) ListComplaints(opts *ListOptions) *ComplaintsIterator

ListComplaints 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) ListCredentials

func (mg *MailgunImpl) ListCredentials(opts *ListOptions) *CredentialsIterator

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

func (*MailgunImpl) ListDomainIPS

func (mg *MailgunImpl) ListDomainIPS(ctx context.Context) ([]IPAddress, error)

ListDomainIPS returns a list of IPs currently assigned to the specified domain.

func (*MailgunImpl) ListDomains

func (mg *MailgunImpl) ListDomains(opts *ListOptions) *DomainsIterator

ListDomains retrieves a set of domains from Mailgun.

func (*MailgunImpl) ListEvents

func (mg *MailgunImpl) ListEvents(opts *ListEventOptions) *EventIterator

Create an new iterator to fetch a page of events from the events api

Example
mg := mailgun.NewMailgun("your-domain.com", "your-api-key")
mg.SetAPIBase(server.URL())

it := mg.ListEvents(&mailgun.ListEventOptions{Limit: 100})

var page []mailgun.Event

// The entire operation should not take longer than 30 seconds
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()

// For each page of 100 events
for it.Next(ctx, &page) {
	for _, e := range page {
		// You can access some fields via the interface
		//fmt.Printf("Event: '%s' TimeStamp: '%s'\n", e.GetName(), e.GetTimestamp())

		// and you can act upon each event by type
		switch event := e.(type) {
		case *events.Accepted:
			fmt.Printf("Accepted: auth: %t\n", event.Flags.IsAuthenticated)
		case *events.Delivered:
			fmt.Printf("Delivered transport: %s\n", event.Envelope.Transport)
		case *events.Failed:
			fmt.Printf("Failed reason: %s\n", event.Reason)
		case *events.Clicked:
			fmt.Printf("Clicked GeoLocation: %s\n", event.GeoLocation.Country)
		case *events.Opened:
			fmt.Printf("Opened GeoLocation: %s\n", event.GeoLocation.Country)
		case *events.Rejected:
			fmt.Printf("Rejected reason: %s\n", event.Reject.Reason)
		case *events.Stored:
			fmt.Printf("Stored URL: %s\n", event.Storage.URL)
		case *events.Unsubscribed:
			fmt.Printf("Unsubscribed client OS: %s\n", event.ClientInfo.ClientOS)
		}
	}
}
// Accepted: auth: false
// Accepted: auth: true
// Delivered transport: smtp
// Delivered transport: http
// Stored URL: http://mailgun.text/some/url
// Clicked GeoLocation: US
// Clicked GeoLocation: US
// Clicked GeoLocation: US
// Opened GeoLocation: US
// Opened GeoLocation: US
// Opened GeoLocation: US
// Unsubscribed client OS: OS X
// Unsubscribed client OS: OS X
Output:

func (*MailgunImpl) ListExports

func (mg *MailgunImpl) ListExports(ctx context.Context, url string) ([]Export, error)

List all exports created within the past 24 hours

func (*MailgunImpl) ListIPS

func (mg *MailgunImpl) ListIPS(ctx context.Context, dedicated bool) ([]IPAddress, error)

ListIPS returns a list of IPs assigned to your account

func (*MailgunImpl) ListMailingLists

func (mg *MailgunImpl) ListMailingLists(opts *ListOptions) *ListsIterator

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

func (*MailgunImpl) ListMembers

func (mg *MailgunImpl) ListMembers(address string, opts *ListOptions) *MemberListIterator

func (*MailgunImpl) ListRoutes

func (mg *MailgunImpl) ListRoutes(opts *ListOptions) *RoutesIterator

ListRoutes allows you to iterate through a list of routes returned by the API

func (*MailgunImpl) ListTags

func (mg *MailgunImpl) ListTags(opts *ListTagOptions) *TagIterator

ListTags returns a cursor used to iterate through a list of tags

it := mg.ListTags(nil)
var page []mailgun.Tag
for it.Next(&page) {
	for _, tag := range(page) {
		// Do stuff with tags
	}
}
if it.Err() != nil {
	log.Fatal(it.Err())
}

func (*MailgunImpl) ListTemplateVersions

func (mg *MailgunImpl) ListTemplateVersions(templateName string, opts *ListOptions) *TemplateVersionsIterator

List all the versions of a specific template

func (*MailgunImpl) ListTemplates

func (mg *MailgunImpl) ListTemplates(opts *ListTemplateOptions) *TemplatesIterator

List all available templates

func (*MailgunImpl) ListUnsubscribes

func (mg *MailgunImpl) ListUnsubscribes(opts *ListOptions) *UnsubscribesIterator

Fetches the list of unsubscribes

func (*MailgunImpl) ListWebhooks

func (mg *MailgunImpl) ListWebhooks(ctx context.Context) (map[string][]string, error)

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

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) PollEvents

func (mg *MailgunImpl) PollEvents(opts *ListEventOptions) *EventPoller

Poll the events api and return new events as they occur

it = mg.PollEvents(&ListEventOptions{
  // Only events with a timestamp after this date/time will be returned
  Begin:        time.Now().Add(time.Second * -3),
  // How often we poll the api for new events
  PollInterval: time.Second * 4
})

var events []Event
ctx, cancel := context.WithCancel(context.Background())

// Blocks until new events appear or context is cancelled
for it.Poll(ctx, &events) {
  for _, event := range(events) {
    fmt.Printf("Event %+v\n", event)
  }
}
if it.Err() != nil {
  log.Fatal(it.Err())
}

func (*MailgunImpl) ReSend added in v3.1.0

func (mg *MailgunImpl) ReSend(ctx context.Context, url string, recipients ...string) (string, string, error)

Given a storage id resend the stored message to the specified recipients

func (*MailgunImpl) Send

func (mg *MailgunImpl) Send(ctx context.Context, 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 := mailgun.NewMailgun("example.com", "my_api_key")

ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()

m := mg.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(ctx, 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!
`

ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()

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

func (*MailgunImpl) SetAPIBase

func (mg *MailgunImpl) SetAPIBase(address string)

SetAPIBase updates the API Base URL for this client.

// For EU Customers
mg.SetAPIBase(mailgun.APIBaseEU)

// For US Customers
mg.SetAPIBase(mailgun.APIBaseUS)

// Set a custom base API
mg.SetAPIBase("https://localhost/v3")

func (*MailgunImpl) SetClient

func (mg *MailgunImpl) SetClient(c *http.Client)

SetClient updates the HTTP client for this client.

func (*MailgunImpl) UpdateClickTracking added in v3.6.0

func (mg *MailgunImpl) UpdateClickTracking(ctx context.Context, domain, active string) error

func (*MailgunImpl) UpdateDomainConnection

func (mg *MailgunImpl) UpdateDomainConnection(ctx context.Context, domain string, settings DomainConnection) error

Updates the specified delivery connection settings for the defined domain

func (*MailgunImpl) UpdateMailingList

func (mg *MailgunImpl) UpdateMailingList(ctx context.Context, addr string, prototype MailingList) (MailingList, error)

UpdateMailingList 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.

func (*MailgunImpl) UpdateMember

func (mg *MailgunImpl) UpdateMember(ctx context.Context, 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) UpdateOpenTracking added in v3.6.0

func (mg *MailgunImpl) UpdateOpenTracking(ctx context.Context, domain, active string) error

func (*MailgunImpl) UpdateRoute

func (mg *MailgunImpl) UpdateRoute(ctx context.Context, 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.

func (*MailgunImpl) UpdateTemplate

func (mg *MailgunImpl) UpdateTemplate(ctx context.Context, template *Template) error

Update the name and description of a template

func (*MailgunImpl) UpdateTemplateVersion

func (mg *MailgunImpl) UpdateTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error

Update the comment and mark a version of a template active

func (*MailgunImpl) UpdateUnsubscribeTracking added in v3.6.0

func (mg *MailgunImpl) UpdateUnsubscribeTracking(ctx context.Context, domain, active, htmlFooter, textFooter string) error

func (*MailgunImpl) UpdateWebhook

func (mg *MailgunImpl) UpdateWebhook(ctx context.Context, kind string, urls []string) error

UpdateWebhook replaces one webhook setting for another.

func (*MailgunImpl) VerifyDomain added in v3.3.0

func (mg *MailgunImpl) VerifyDomain(ctx context.Context, domain string) (string, error)

func (*MailgunImpl) VerifyWebhookRequest deprecated

func (mg *MailgunImpl) VerifyWebhookRequest(req *http.Request) (verified bool, err error)

Deprecated: Please use the VerifyWebhookSignature() to parse the latest version of WebHooks from mailgun

func (*MailgunImpl) VerifyWebhookSignature added in v3.2.0

func (mg *MailgunImpl) VerifyWebhookSignature(sig Signature) (verified bool, err error)

Use this method to parse the webhook signature given as JSON in the webhook response

Example
// Create an instance of the Mailgun Client
mg, err := mailgun.NewMailgunFromEnv()
if err != nil {
	fmt.Printf("mailgun error: %s\n", err)
	os.Exit(1)
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

	var payload mailgun.WebhookPayload
	if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
		fmt.Printf("decode JSON error: %s", err)
		w.WriteHeader(http.StatusNotAcceptable)
		return
	}

	verified, err := mg.VerifyWebhookSignature(payload.Signature)
	if err != nil {
		fmt.Printf("verify error: %s\n", err)
		w.WriteHeader(http.StatusNotAcceptable)
		return
	}

	if !verified {
		w.WriteHeader(http.StatusNotAcceptable)
		fmt.Printf("failed verification %+v\n", payload.Signature)
		return
	}

	fmt.Printf("Verified Signature\n")

	// Parse the raw event to extract the

	e, err := mailgun.ParseEvent(payload.EventData)
	if err != nil {
		fmt.Printf("parse event error: %s\n", err)
		return
	}

	switch event := e.(type) {
	case *events.Accepted:
		fmt.Printf("Accepted: auth: %t\n", event.Flags.IsAuthenticated)
	case *events.Delivered:
		fmt.Printf("Delivered transport: %s\n", event.Envelope.Transport)
	}
})

fmt.Println("Running...")
if err := http.ListenAndServe(":9090", nil); err != nil {
	fmt.Printf("serve error: %s\n", err)
	os.Exit(1)
}
Output:

type MailingList

type MailingList struct {
	Address      string      `json:"address,omitempty"`
	Name         string      `json:"name,omitempty"`
	Description  string      `json:"description,omitempty"`
	AccessLevel  AccessLevel `json:"access_level,omitempty"`
	CreatedAt    RFC2822Time `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 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 MemberListIterator

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

func (*MemberListIterator) Err

func (li *MemberListIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*MemberListIterator) First

func (li *MemberListIterator) First(ctx context.Context, items *[]Member) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*MemberListIterator) Last

func (li *MemberListIterator) Last(ctx context.Context, items *[]Member) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*MemberListIterator) Next

func (li *MemberListIterator) Next(ctx context.Context, items *[]Member) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*MemberListIterator) Previous

func (li *MemberListIterator) Previous(ctx context.Context, items *[]Member) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

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 (*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) AddBufferAttachment

func (m *Message) AddBufferAttachment(filename string, buffer []byte)

AddBufferAttachment arranges to send a file along with the e-mail message. File contents are read from the []byte array provided The filename parameter is the resulting filename of the attachment. The buffer parameter is the []byte array which contains the actual bytes to be used as the contents of the attached file.

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)

AddCampaign is no longer supported and is deprecated for new software.

func (*Message) AddDomain

func (m *Message) AddDomain(domain string)

AddDomain allows you to use a separate domain for the type of messages you are sending.

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) AddReaderInline

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

AddReaderInline 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. It will return an error if the limit of recipients have been exceeded for this message

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. It will return an error if the limit of recipients have been exceeded for this message

func (*Message) AddTag

func (m *Message) AddTag(tag ...string) error

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

func (*Message) AddTemplateVariable added in v3.6.2

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

AddTemplateVariable adds a template variable to the map of template variables, replacing the variable if it is already there. This is used for server-side message templates and can nest arbitrary values. At send time, the resulting map will be converted into a JSON string and sent as a header in the X-Mailgun-Variables header.

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) EnableNativeSend

func (m *Message) EnableNativeSend()

EnableNativeSend allows the return path to match the address in the Message.Headers.From: field when sending from Mailgun rather than the usual bounce+ address in the return path.

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) GetHeaders added in v3.3.1

func (m *Message) GetHeaders() map[string]string

GetHeaders retrieves the http headers associated with this message

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)

SetHtml is a helper. 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) SetReplyTo

func (m *Message) SetReplyTo(recipient string)

SetReplyTo sets the receiver who should receive replies

func (*Message) SetRequireTLS added in v3.1.0

func (m *Message) SetRequireTLS(b bool)

SetRequireTLS information is found in the Mailgun documentation.

func (*Message) SetSkipVerification added in v3.1.0

func (m *Message) SetSkipVerification(b bool)

SetSkipVerification information is found in the Mailgun documentation.

func (*Message) SetTemplate added in v3.4.0

func (m *Message) SetTemplate(t string)

SetTemplate sets the name of a template stored via the template API. See https://documentation.mailgun.com/en/latest/user_manual.html#templating

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)

SetTrackingClicks information is found in the Mailgun documentation.

func (*Message) SetTrackingOpens

func (m *Message) SetTrackingOpens(trackingOpens bool)

SetTrackingOpens information is found in the Mailgun documentation.

type MockServer

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

A mailgun api mock suitable for testing

func NewMockServer

func NewMockServer() MockServer

Create a new instance of the mailgun API mock server

func (*MockServer) Stop

func (ms *MockServer) Stop()

Stop the server

func (*MockServer) URL

func (ms *MockServer) URL() string

URL returns the URL used to connect to the mock server

type Paging

type Paging struct {
	First    string `json:"first,omitempty"`
	Next     string `json:"next,omitempty"`
	Previous string `json:"previous,omitempty"`
	Last     string `json:"last,omitempty"`
}

type Permanent

type Permanent struct {
	SuppressBounce      int `json:"suppress-bounce"`
	SuppressUnsubscribe int `json:"suppress-unsubscribe"`
	SuppressComplaint   int `json:"suppress-complaint"`
	Bounce              int `json:"bounce"`
	DelayedBounce       int `json:"delayed-bounce"`
	Total               int `json:"total"`
}

Stats on permanent failures

type RFC2822Time

type RFC2822Time time.Time

Mailgun uses RFC2822 format for timestamps everywhere ('Thu, 13 Oct 2011 18:02:00 GMT'), but by default Go's JSON package uses another format when decoding/encoding timestamps.

func NewRFC2822Time

func NewRFC2822Time(str string) (RFC2822Time, error)

func (RFC2822Time) IsZero

func (t RFC2822Time) IsZero() bool

func (RFC2822Time) MarshalJSON

func (t RFC2822Time) MarshalJSON() ([]byte, error)

func (RFC2822Time) String

func (t RFC2822Time) String() string

func (RFC2822Time) Unix

func (t RFC2822Time) Unix() int64

func (*RFC2822Time) UnmarshalJSON

func (t *RFC2822Time) UnmarshalJSON(s []byte) error

type ReaderAttachment

type ReaderAttachment struct {
	Filename   string
	ReadCloser io.ReadCloser
}

type Recipient

type Recipient struct {
	Name  string `json:"-"`
	Email string `json:"-"`
}

func (Recipient) MarshalText

func (r Recipient) MarshalText() ([]byte, error)

MarshalText satisfies TextMarshaler

func (Recipient) String

func (r Recipient) String() string

func (*Recipient) UnmarshalText

func (r *Recipient) UnmarshalText(text []byte) error

UnmarshalText satisfies TextUnmarshaler

type Resolution

type Resolution string

Used by GetStats() to specify the resolution stats are for

type Route

type Route struct {
	// The Priority field indicates how soon the route works relative to other configured routes.
	// Routes of equal priority are consulted in chronological order.
	Priority int `json:"priority,omitempty"`
	// 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.
	Description string `json:"description,omitempty"`
	// The Expression field lets you specify a pattern to match incoming messages against.
	Expression string `json:"expression,omitempty"`
	// The Actions field contains strings specifying what to do
	// with any message which matches the provided expression.
	Actions []string `json:"actions,omitempty"`

	// The CreatedAt field provides a time-stamp for when the route came into existence.
	CreatedAt RFC2822Time `json:"created_at,omitempty"`
	// ID field provides a unique identifier for this route.
	Id string `json:"id,omitempty"`
}

A Route structure contains information on a configured or to-be-configured 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 RoutesIterator

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

func (*RoutesIterator) Err

func (ri *RoutesIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*RoutesIterator) First

func (ri *RoutesIterator) First(ctx context.Context, items *[]Route) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*RoutesIterator) Last

func (ri *RoutesIterator) Last(ctx context.Context, items *[]Route) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*RoutesIterator) Next

func (ri *RoutesIterator) Next(ctx context.Context, items *[]Route) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*RoutesIterator) Offset

func (ri *RoutesIterator) Offset() int

Offset returns the current offset of the iterator

func (*RoutesIterator) Previous

func (ri *RoutesIterator) Previous(ctx context.Context, items *[]Route) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type Signature added in v3.2.0

type Signature struct {
	TimeStamp string `json:"timestamp"`
	Token     string `json:"token"`
	Signature string `json:"signature"`
}

Represents the signature portion of the webhook POST body

type SpamAction

type SpamAction string

type Stats

type Stats struct {
	Time         string    `json:"time"`
	Accepted     Accepted  `json:"accepted"`
	Delivered    Delivered `json:"delivered"`
	Failed       Failed    `json:"failed"`
	Stored       Total     `json:"stored"`
	Opened       Total     `json:"opened"`
	Clicked      Total     `json:"clicked"`
	Unsubscribed Total     `json:"unsubscribed"`
	Complained   Total     `json:"complained"`
}

Stats as returned by `GetStats()`

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]struct {
		Url         string `json:"url"`
		ContentType string `json:"content-type"`
		Name        string `json:"name"`
		Size        int64  `json:"size"`
	} `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 Tag

type Tag struct {
	Value       string     `json:"tag"`
	Description string     `json:"description"`
	FirstSeen   *time.Time `json:"first-seen,omitempty"`
	LastSeen    *time.Time `json:"last-seen,omitempty"`
}

type TagIterator

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

func (*TagIterator) Err

func (ti *TagIterator) Err() error

Err returns any error if one occurred

func (*TagIterator) First

func (ti *TagIterator) First(ctx context.Context, items *[]Tag) bool

First returns the first page in the list of tags

func (*TagIterator) Last

func (ti *TagIterator) Last(ctx context.Context, items *[]Tag) bool

Last returns the last page in the list of tags

func (*TagIterator) Next

func (ti *TagIterator) Next(ctx context.Context, items *[]Tag) bool

Next returns the next page in the list of tags

func (*TagIterator) Previous

func (ti *TagIterator) Previous(ctx context.Context, items *[]Tag) bool

Previous returns the previous page in the list of tags

type TagLimits

type TagLimits struct {
	Limit int `json:"limit"`
	Count int `json:"count"`
}

type Template

type Template struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	CreatedAt   RFC2822Time     `json:"createdAt"`
	Version     TemplateVersion `json:"version,omitempty"`
}

type TemplateEngine

type TemplateEngine string

type TemplateVersion

type TemplateVersion struct {
	Tag       string         `json:"tag"`
	Template  string         `json:"template,omitempty"`
	Engine    TemplateEngine `json:"engine"`
	CreatedAt RFC2822Time    `json:"createdAt"`
	Comment   string         `json:"comment"`
	Active    bool           `json:"active"`
}

type TemplateVersionsIterator

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

func (*TemplateVersionsIterator) Err

func (li *TemplateVersionsIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*TemplateVersionsIterator) First

func (li *TemplateVersionsIterator) First(ctx context.Context, items *[]TemplateVersion) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*TemplateVersionsIterator) Last

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*TemplateVersionsIterator) Next

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*TemplateVersionsIterator) Previous

func (li *TemplateVersionsIterator) Previous(ctx context.Context, items *[]TemplateVersion) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type TemplatesIterator

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

func (*TemplatesIterator) Err

func (ti *TemplatesIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*TemplatesIterator) First

func (ti *TemplatesIterator) First(ctx context.Context, items *[]Template) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*TemplatesIterator) Last

func (ti *TemplatesIterator) Last(ctx context.Context, items *[]Template) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*TemplatesIterator) Next

func (ti *TemplatesIterator) Next(ctx context.Context, items *[]Template) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*TemplatesIterator) Previous

func (ti *TemplatesIterator) Previous(ctx context.Context, items *[]Template) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type Temporary

type Temporary struct {
	Espblock int `json:"espblock"`
}

Stats on temporary failures

type Total

type Total struct {
	Total int `json:"total"`
}

Total stats for messages

type TrackingStatus

type TrackingStatus struct {
	Active     bool   `json:"active"`
	HTMLFooter string `json:"html_footer"`
	TextFooter string `json:"text_footer"`
}

The tracking status of a domain

type UnexpectedResponseError

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

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 Unsubscribe

type Unsubscribe struct {
	CreatedAt RFC2822Time `json:"created_at"`
	Tags      []string    `json:"tags"`
	ID        string      `json:"id"`
	Address   string      `json:"address"`
}

type UnsubscribesIterator

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

func (*UnsubscribesIterator) Err

func (ci *UnsubscribesIterator) Err() error

If an error occurred during iteration `Err()` will return non nil

func (*UnsubscribesIterator) First

func (ci *UnsubscribesIterator) First(ctx context.Context, items *[]Unsubscribe) bool

First retrieves the first page of items from the api. Returns false if there was an error. It also sets the iterator object to the first page. Use `.Err()` to retrieve the error.

func (*UnsubscribesIterator) Last

func (ci *UnsubscribesIterator) Last(ctx context.Context, items *[]Unsubscribe) bool

Last retrieves the last page of items from the api. Calling Last() is invalid unless you first call First() or Next() Returns false if there was an error. It also sets the iterator object to the last page. Use `.Err()` to retrieve the error.

func (*UnsubscribesIterator) Next

func (ci *UnsubscribesIterator) Next(ctx context.Context, items *[]Unsubscribe) bool

Next retrieves the next page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error

func (*UnsubscribesIterator) Previous

func (ci *UnsubscribesIterator) Previous(ctx context.Context, items *[]Unsubscribe) bool

Previous retrieves the previous page of items from the api. Returns false when there no more pages to retrieve or if there was an error. Use `.Err()` to retrieve the error if any

type UrlOrUrls added in v3.5.0

type UrlOrUrls struct {
	Urls []string `json:"urls"`
	Url  string   `json:"url"`
}

type WebHookResponse added in v3.5.0

type WebHookResponse struct {
	Webhook UrlOrUrls `json:"webhook"`
}

type WebHooksListResponse added in v3.5.0

type WebHooksListResponse struct {
	Webhooks map[string]UrlOrUrls `json:"webhooks"`
}

type WebhookPayload added in v3.2.0

type WebhookPayload struct {
	Signature Signature      `json:"signature"`
	EventData events.RawJSON `json:"event-data"`
}

Represents the JSON payload provided when a Webhook is called by mailgun

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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