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> Version: 0.99.0
Examples ¶
This document includes a number of examples which illustrates some aspects of the GUI which might be misleading or confusing. All examples included are derived from an acceptance test. Note that every SDK function has a corresponding acceptance test, so if you don't find an example for a function you'd like to know more about, please check the acceptance sub-package for a corresponding test. Of course, contributions to the documentation are always welcome as well. Feel free to submit a pull request or open a Github issue if you cannot find an example to suit your needs.
Limit and Skip Settings ¶
Many SDK functions consume a pair of parameters called limit and skip. These help control how much data Mailgun sends over the wire. Limit, as you'd expect, gives a count of the number of records you want to receive. Note that, at present, Mailgun imposes its own cap of 100, for all API endpoints. Skip indicates where in the data set you want to start receiving from. Mailgun defaults to the very beginning of the dataset if not specified explicitly.
If you don't particularly care how much data you receive, you may specify DefaultLimit. If you similarly don't care about where the data starts, you may specify DefaultSkip.
Functions that Return Totals ¶
Functions which accept a limit and skip setting, in general, will also return a total count of the items returned. Note that this total count is not the total in the bundle returned by the call. You can determine that easily enough with Go's len() function. The total that you receive actually refers to the complete set of data on the server. This total may well exceed the size returned from the API.
If this happens, you may find yourself needing to iterate over the dataset of interest. For example:
// Get total amount of stuff we have to work with. mg := NewMailgun("example.com", "my_api_key", "") n, _, err := mg.GetStats(1, 0, nil, "sent", "opened") if err != nil { t.Fatal(err) } // Loop over it all. for sk := 0; sk < n; sk += limit { _, stats, err := mg.GetStats(limit, sk, nil, "sent", "opened") if err != nil { t.Fatal(err) } doSomethingWith(stats) }
License ¶
Copyright (c) 2013-2014, Michael Banzon. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the names of Mailgun, Michael Banzon, nor the names of their contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Index ¶
- Constants
- Variables
- func GetStatusFromErr(err error) int
- type Accepted
- type Batch
- type Bounce
- type BufferAttachment
- type ClientInfo
- type ClientType
- type Complaint
- type Credential
- type DNSRecord
- type Delivered
- type DeliveryStatus
- type DeviceType
- type Domain
- type EmailValidator
- type EmailValidatorImpl
- func (m *EmailValidatorImpl) APIBase() string
- func (m *EmailValidatorImpl) APIKey() string
- func (m *EmailValidatorImpl) Client() *http.Client
- func (m *EmailValidatorImpl) ParseAddresses(addresses ...string) ([]string, []string, error)
- func (m *EmailValidatorImpl) SetAPIBase(address string)
- func (m *EmailValidatorImpl) SetClient(c *http.Client)
- func (m *EmailValidatorImpl) ValidateEmail(email string, mailBoxVerify bool) (EmailVerification, error)
- type EmailVerification
- type EmailVerificationParts
- type Envelope
- type Event
- type EventFlags
- type EventIterator
- func (ei *EventIterator) Err() error
- func (ei *EventIterator) First(events *[]Event) bool
- func (ei *EventIterator) GetFirstPage(opts GetEventsOptions) error
- func (ei *EventIterator) GetNext() error
- func (ei *EventIterator) GetPrevious() error
- func (ei *EventIterator) Last(events *[]Event) bool
- func (ei *EventIterator) Next(events *[]Event) bool
- func (ei *EventIterator) Previous(events *[]Event) bool
- type EventMessage
- type EventPoller
- type EventReason
- type EventSeverity
- type EventType
- type EventsOptions
- type Failed
- type Geolocation
- type GetEventsOptions
- type IP
- type List
- type Mailgun
- type MailgunImpl
- func (m *MailgunImpl) APIBase() string
- func (m *MailgunImpl) APIKey() string
- func (m *MailgunImpl) AddBounce(address, code, error string) error
- func (mg *MailgunImpl) ChangeCredentialPassword(id, password string) error
- func (m *MailgunImpl) Client() *http.Client
- func (m *MailgunImpl) CreateComplaint(address string) error
- func (mg *MailgunImpl) CreateCredential(login, password string) error
- func (m *MailgunImpl) CreateDomain(name string, smtpPassword string, spamAction string, wildcard bool) error
- func (mg *MailgunImpl) CreateList(prototype List) (List, error)
- func (mg *MailgunImpl) CreateMember(merge bool, addr string, prototype Member) error
- func (mg *MailgunImpl) CreateMemberList(u *bool, addr string, newMembers []interface{}) error
- func (mg *MailgunImpl) CreateRoute(prototype Route) (_ignored Route, err error)
- func (mg *MailgunImpl) CreateWebhook(t, u string) error
- func (m *MailgunImpl) DeleteBounce(address string) error
- func (m *MailgunImpl) DeleteComplaint(address string) error
- func (mg *MailgunImpl) DeleteCredential(id string) error
- func (m *MailgunImpl) DeleteDomain(name string) error
- func (mg *MailgunImpl) DeleteList(addr string) error
- func (mg *MailgunImpl) DeleteMember(member, addr string) error
- func (mg *MailgunImpl) DeleteRoute(id string) error
- func (mg *MailgunImpl) DeleteStoredMessage(id string) error
- func (m *MailgunImpl) DeleteTag(tag string) error
- func (mg *MailgunImpl) DeleteWebhook(t string) error
- func (m *MailgunImpl) Domain() string
- func (m *MailgunImpl) GetBounces(limit, skip int) (int, []Bounce, error)
- func (m *MailgunImpl) GetComplaints(limit, skip int) (int, []Complaint, error)
- func (mg *MailgunImpl) GetCredentials(limit, skip int) (int, []Credential, error)
- func (m *MailgunImpl) GetDomains(limit, skip int) (int, []Domain, error)
- func (mg *MailgunImpl) GetListByAddress(addr string) (List, error)
- func (mg *MailgunImpl) GetLists(limit, skip int, filter string) (int, []List, error)
- func (mg *MailgunImpl) GetMemberByAddress(s, l string) (Member, error)
- func (mg *MailgunImpl) GetMembers(limit, skip int, s *bool, addr string) (int, []Member, error)
- func (mg *MailgunImpl) GetRouteByID(id string) (Route, error)
- func (mg *MailgunImpl) GetRoutes(limit, skip int) (int, []Route, error)
- func (m *MailgunImpl) GetSingleBounce(address string) (Bounce, error)
- func (m *MailgunImpl) GetSingleComplaint(address string) (Complaint, error)
- func (m *MailgunImpl) GetSingleDomain(domain string) (Domain, []DNSRecord, []DNSRecord, error)
- func (m *MailgunImpl) GetStats(limit int, skip int, startDate *time.Time, event ...string) (int, []Stat, error)
- func (m *MailgunImpl) GetStatsTotal(start *time.Time, end *time.Time, resolution string, duration string, ...) (*StatsTotalResponse, error)
- func (mg *MailgunImpl) GetStoredMessage(id string) (StoredMessage, error)
- func (mg *MailgunImpl) GetStoredMessageForURL(url string) (StoredMessage, error)
- func (mg *MailgunImpl) GetStoredMessageRaw(id string) (StoredMessageRaw, error)
- func (mg *MailgunImpl) GetStoredMessageRawForURL(url string) (StoredMessageRaw, error)
- func (m *MailgunImpl) GetTag(tag string) (TagItem, error)
- func (mg *MailgunImpl) GetUnsubscribes(limit, skip int) (int, []Unsubscription, error)
- func (mg *MailgunImpl) GetUnsubscribesByAddress(a string) (int, []Unsubscription, error)
- func (mg *MailgunImpl) GetWebhookByType(t string) (string, error)
- func (mg *MailgunImpl) GetWebhooks() (map[string]string, error)
- func (mg *MailgunImpl) ListEvents(opts *EventsOptions) *EventIterator
- func (m *MailgunImpl) ListTags(opts *TagOptions) *TagIterator
- func (mg *MailgunImpl) NewEventIterator() *EventIterator
- func (mg *MailgunImpl) NewMIMEMessage(body io.ReadCloser, to ...string) *Message
- func (mg *MailgunImpl) NewMessage(from, subject, text string, to ...string) *Message
- func (mg *MailgunImpl) PollEvents(opts *EventsOptions) *EventPoller
- func (mg *MailgunImpl) RemoveUnsubscribe(a string) error
- func (mg *MailgunImpl) RemoveUnsubscribeWithTag(a, t string) error
- func (m *MailgunImpl) Send(message *Message) (mes string, id string, err error)
- func (m *MailgunImpl) SetAPIBase(address string)
- func (m *MailgunImpl) SetClient(c *http.Client)
- func (mg *MailgunImpl) Unsubscribe(a, t string) error
- func (mg *MailgunImpl) UpdateList(addr string, prototype List) (List, error)
- func (mg *MailgunImpl) UpdateMember(s, l string, prototype Member) (Member, error)
- func (mg *MailgunImpl) UpdateRoute(id string, route Route) (Route, error)
- func (mg *MailgunImpl) UpdateWebhook(t, u string) error
- func (mg *MailgunImpl) VerifyWebhookRequest(req *http.Request) (verified bool, err error)
- type MailingList
- type MailingListError
- type MailingListMember
- type Member
- type Message
- func (m *Message) AddAttachment(attachment string)
- func (m *Message) AddBCC(recipient string)
- func (m *Message) AddBufferAttachment(filename string, buffer []byte)
- func (m *Message) AddCC(recipient string)
- func (m *Message) AddCampaign(campaign string)
- func (m *Message) AddDomain(domain string)
- func (m *Message) AddHeader(header, value string)
- func (m *Message) AddInline(inline string)
- func (m *Message) AddReaderAttachment(filename string, readCloser io.ReadCloser)
- func (m *Message) AddReaderInline(filename string, readCloser io.ReadCloser)
- func (m *Message) AddRecipient(recipient string) error
- func (m *Message) AddRecipientAndVariables(r string, vars map[string]interface{}) error
- func (m *Message) AddTag(tag string)
- func (m *Message) AddVariable(variable string, value interface{}) error
- func (m *Message) EnableNativeSend()
- func (m *Message) EnableTestMode()
- func (m *Message) RecipientCount() int
- func (m *Message) SetDKIM(dkim bool)
- func (m *Message) SetDeliveryTime(dt time.Time)
- func (m *Message) SetHtml(html string)
- func (m *Message) SetReplyTo(recipient string)
- func (m *Message) SetTracking(tracking bool)
- func (m *Message) SetTrackingClicks(trackingClicks bool)
- func (m *Message) SetTrackingOpens(trackingOpens bool)
- type Method
- type Paging
- type Permanent
- type ReaderAttachment
- type Recipient
- type Route
- type Stat
- type StatsTotal
- type StatsTotalResponse
- type Storage
- type StoredAttachment
- type StoredMessage
- type StoredMessageRaw
- type TagItem
- type TagIterator
- type TagOptions
- type TagsPage
- type Temporary
- type TimestampNano
- type Total
- type TransportMethod
- type UnexpectedResponseError
- type Unsubscription
Examples ¶
Constants ¶
const ( DefaultLimit = -1 DefaultSkip = -1 )
DefaultLimit and DefaultSkip instruct the SDK to rely on Mailgun's reasonable defaults for Paging settings.
const ( Tag = "tag" Disabled = "disabled" Delete = "delete" )
Disabled, Tag, and Delete indicate spam actions. Disabled prevents Mailgun from taking any action on what it perceives to be spam. Tag instruments the received message with headers providing a measure of its spamness. Delete instructs Mailgun to just block or delete the message all-together.
const ( ReadOnly = "readonly" Members = "members" Everyone = "everyone" )
A mailing list may have one of three membership modes. ReadOnly specifies that nobody, including Members, may send messages to the mailing list. Messages distributed on such lists come from list administrator accounts only. Members specifies that only those who subscribe to the mailing list may send messages. Everyone specifies that anyone and everyone may both read and submit messages to the mailing list, including non-subscribers.
const (
ApiBase = "https://api.mailgun.net/v3"
)
const MailgunGoUserAgent = "mailgun-go/1.0.0"
The MailgunGoUserAgent identifies the client to the server, for logging purposes. In the event of problems requiring a human administrator's assistance, this user agent allows them to identify the client from human-generated activity.
const MaxNumberOfRecipients = 1000
MaxNumberOfRecipients represents the largest batch of recipients that Mailgun can support in a single API call. This figure includes To:, Cc:, Bcc:, etc. recipients.
Variables ¶
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.
var Debug = false
var ENV = envy.Get("GO_ENV", "development")
ENV is used to help switch settings based on where the application is being run. Default is "development".
var ErrEmptyParam = fmt.Errorf("empty or illegal parameter")
ErrEmptyParam results occur when a required parameter is missing.
Functions ¶
func GetStatusFromErr ¶ added in v1.1.0
Extract the http status code from error object
Types ¶
type Bounce ¶
type Bounce struct { CreatedAt string `json:"created_at"` Code interface{} `json:"code"` Address string `json:"address"` Error string `json:"error"` }
Bounce aggregates data relating to undeliverable messages to a specific intended recipient, identified by Address. Code provides the SMTP error code causing the bounce, while Error provides a human readable reason why. CreatedAt provides the time at which Mailgun detected the bounce.
type BufferAttachment ¶ added in v1.1.1
type ClientInfo ¶ added in v1.1.1
type ClientInfo struct { ClientType *ClientType `json:"client-type,omitempty"` ClientOS *string `json:"client-os,omitempty"` ClientName *string `json:"client-name,omitempty"` DeviceType *DeviceType `json:"device-type,omitempty"` UserAgent *string `json:"user-agent,omitempty"` }
type ClientType ¶ added in v1.1.1
type ClientType uint
const ( ClientUnknown ClientType = iota ClientMobileBrowser ClientBrowser ClientEmail ClientLibrary ClientRobot ClientOther )
func (ClientType) MarshalText ¶ added in v1.1.1
func (ct ClientType) MarshalText() ([]byte, error)
MarshalText satisfies TextMarshaler
func (ClientType) String ¶ added in v1.1.1
func (ct ClientType) String() string
func (*ClientType) UnmarshalText ¶ added in v1.1.1
func (ct *ClientType) UnmarshalText(text []byte) error
UnmarshalText satisfies TextUnmarshaler
type Complaint ¶
type Complaint struct { Count int `json:"count"` CreatedAt string `json:"created_at"` Address string `json:"address"` }
Complaint structures track how many times one of your emails have been marked as spam. CreatedAt indicates when the first report arrives from a given recipient, identified by Address. Count provides a running counter of how many times the recipient thought your messages were not solicited.
type Credential ¶
type Credential struct { CreatedAt string `json:"created_at"` Login string `json:"login"` Password string `json:"password"` }
A Credential structure describes a principle allowed to send or receive mail at the domain.
type DNSRecord ¶
type DNSRecord struct { Priority string RecordType string `json:"record_type"` Valid string Name string Value string }
DNSRecord structures describe intended records to properly configure your domain for use with Mailgun. Note that Mailgun does not host DNS records.
type DeliveryStatus ¶ added in v1.1.1
type DeviceType ¶ added in v1.1.1
type DeviceType uint
const ( DeviceUnknown DeviceType = iota DeviceMobileBrowser DeviceBrowser DeviceEmail DeviceOther )
func (DeviceType) MarshalText ¶ added in v1.1.1
func (ct DeviceType) MarshalText() ([]byte, error)
MarshalText satisfies TextMarshaler
func (DeviceType) String ¶ added in v1.1.1
func (ct DeviceType) String() string
func (*DeviceType) UnmarshalText ¶ added in v1.1.1
func (ct *DeviceType) UnmarshalText(text []byte) error
UnmarshalText satisfies TextUnmarshaler
type Domain ¶
type Domain struct { CreatedAt string `json:"created_at"` SMTPLogin string `json:"smtp_login"` Name string `json:"name"` SMTPPassword string `json:"smtp_password"` Wildcard bool `json:"wildcard"` SpamAction string `json:"spam_action"` }
A Domain structure holds information about a domain used when sending mail. The SpamAction field must be one of Tag, Disabled, or Delete.
type EmailValidator ¶
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)
Return 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
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(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(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 { IsValid bool `json:"is_valid"` MailboxVerification string `json:"mailbox_verification"` Parts EmailVerificationParts `json:"parts"` Address string `json:"address"` DidYouMean string `json:"did_you_mean"` IsDisposableAddress bool `json:"is_disposable_address"` IsRoleAddress bool `json:"is_role_address"` Reason string `json:"reason"` }
EmailVerification records basic facts about a validated e-mail address. See the ValidateEmail method and example for more details.
IsValid indicates whether an email address conforms to IETF RFC standards. MailboxVerification indicates whether an email address is deliverable. Parts records the different subfields of an email address. Address echoes the address provided. DidYouMean provides a simple recommendation in case the address is invalid or Mailgun thinks you might have a typo. DidYouMean may be empty (""), in which case Mailgun has no recommendation to give. The existence of DidYouMean does NOT imply the email provided has anything wrong with it. IsDisposableAddress indicates whether Mailgun thinks the address is from a known disposable mailbox provider. IsRoleAddress indicates whether Mailgun thinks the address is an email distribution list. Reason contains error's description.
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 Envelope ¶ added in v1.1.1
type Envelope struct { Sender *string `json:"sender,omitempty"` SendingHost *string `json:"sending-host,omitempty"` SendingIP *IP `json:"sending-ip,omitempty"` Targets *string `json:"targets,omitempty"` Transport *TransportMethod `json:"transport,omitempty"` }
type Event ¶
type Event struct { // Mandatory fields present in each event ID string `json:"id"` Timestamp TimestampNano `json:"timestamp"` Event EventType `json:"event"` // Delivery related values DeliveryStatus *DeliveryStatus `json:"delivery-status,omitempty"` Reason *EventReason `json:"reason,omitempty"` Severity *EventSeverity `json:"severity,omitempty"` // Message classification / grouping Tags []string `json:"tags,omitempty"` // Recipient information (for recipient-initiated events: opens, clicks etc) ClientInfo *ClientInfo `json:"client-info,omitempty"` Geolocation *Geolocation `json:"geolocation,omitempty"` IP *IP `json:"ip,omitempty"` Envelope *Envelope `json:"envelope,omitempty"` // Clicked URL *string `json:"url,omitempty"` // Message // TODO: unify message types Message *EventMessage `json:"message,omitempty"` Batch *Batch `json:"batch,omitempty"` Recipient *Recipient `json:"recipient,omitempty"` Routes []Route `json:"routes,omitempty"` Storage *Storage `json:"storage,omitempty"` UserVariables map[string]string `json:"user-variables"` // API Method *Method `json:"method,omitempty"` Flags *EventFlags `json:"flags,omitempty"` // Mailing List MailingList MailingList `json:"mailing-list,omitempty"` Member MailingListMember `json:"member,omitempty"` MemberDescription string `json:"member-description"` Error MailingListError `json:"error"` IsUpsert bool `json:"is-upsert"` Format string `json:"format"` UpsertedCount int `json:"upserted-count"` FailedCount int `json:"failed-count"` Subscribed bool `json:"subscribed"` TaskID string `json:"task-id"` }
type EventFlags ¶ added in v1.1.1
type EventIterator ¶
type EventIterator struct {
// contains filtered or unexported fields
}
EventIterator maintains the state necessary for paging though small parcels of a larger set of events.
func (*EventIterator) Err ¶ added in v1.1.0
func (ei *EventIterator) Err() error
If an error occurred during iteration `Err()` will return non nil
func (*EventIterator) First ¶ added in v1.1.0
func (ei *EventIterator) First(events *[]Event) bool
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) GetFirstPage ¶
func (ei *EventIterator) GetFirstPage(opts GetEventsOptions) error
GetFirstPage retrieves the first batch of events, according to your criteria. See the GetEventsOptions structure for more details on how the fields affect the data returned.
func (*EventIterator) GetNext ¶
func (ei *EventIterator) GetNext() error
Retrieves the chronologically next batch of events, if any exist. You know you're at the end of the list when len(Events())==0.
func (*EventIterator) GetPrevious ¶
func (ei *EventIterator) GetPrevious() error
Retrieves the chronologically previous batch of events, if any exist. You know you're at the end of the list when len(Events())==0.
func (*EventIterator) Last ¶ added in v1.1.0
func (ei *EventIterator) Last(events *[]Event) bool
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 ¶ added in v1.1.0
func (ei *EventIterator) Next(events *[]Event) bool
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 ¶ added in v1.1.0
func (ei *EventIterator) Previous(events *[]Event) bool
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 EventMessage ¶ added in v1.1.1
type EventMessage struct { Headers map[string]string `json:"headers,omitempty"` Recipients []string `json:"recipients,omitempty"` Attachments []StoredAttachment `json:"attachments,omitempty"` Size *int `json:"size,omitempty"` }
func (*EventMessage) ID ¶ added in v1.1.1
func (em *EventMessage) ID() (string, error)
type EventPoller ¶ added in v1.1.0
type EventPoller struct {
// contains filtered or unexported fields
}
EventPoller maintains the state necessary for polling events
func (*EventPoller) Err ¶ added in v1.1.0
func (ep *EventPoller) Err() error
If an error occurred during polling `Err()` will return non nil
func (*EventPoller) Poll ¶ added in v1.1.0
func (ep *EventPoller) Poll(events *[]Event) bool
type EventReason ¶ added in v1.1.1
type EventReason uint8
const ( ReasonUnknown EventReason = iota ReasonGeneric ReasonBounce ReasonESPBlock ReasonGreylisted ReasonBlacklisted ReasonSuppressBounce ReasonSuppressComplaint ReasonSuppressUnsubscribe ReasonOld ReasonHardFail )
func (EventReason) MarshalText ¶ added in v1.1.1
func (er EventReason) MarshalText() ([]byte, error)
MarshalText satisfies TextMarshaler
func (EventReason) String ¶ added in v1.1.1
func (er EventReason) String() string
func (*EventReason) UnmarshalText ¶ added in v1.1.1
func (er *EventReason) UnmarshalText(text []byte) error
UnmarshalText satisfies TextUnmarshaler
type EventSeverity ¶ added in v1.1.1
type EventSeverity uint8
const ( SeverityUnknown EventSeverity = iota SeverityTemporary SeverityPermanent SeverityInternal )
func (EventSeverity) MarshalText ¶ added in v1.1.1
func (es EventSeverity) MarshalText() ([]byte, error)
MarshalText satisfies TextMarshaler
func (EventSeverity) String ¶ added in v1.1.1
func (es EventSeverity) String() string
func (*EventSeverity) UnmarshalText ¶ added in v1.1.1
func (es *EventSeverity) UnmarshalText(text []byte) error
UnmarshalText satisfies TextUnmarshaler
type EventType ¶ added in v1.1.1
type EventType uint8
func (EventType) MarshalText ¶ added in v1.1.1
MarshalText satisfies TextMarshaler
func (*EventType) UnmarshalText ¶ added in v1.1.1
UnmarshalText satisfies TextUnmarshaler
type EventsOptions ¶ added in v1.1.0
type EventsOptions struct {
Begin, End *time.Time
ForceAscending, ForceDescending, Compact bool
Limit int
Filter map[string]string
ThresholdAge time.Duration
PollInterval time.Duration
}
GetEventsOptions lets the caller of GetEvents() specify how the results are to be returned. Begin and End time-box the results returned. ForceAscending and ForceDescending are used to force Mailgun to use a given traversal order of the events. If both ForceAscending and ForceDescending are true, an error will result. If none, the default will be inferred from the Begin and End parameters. Limit caps the number of results returned. If left unspecified, Mailgun assumes 100. Compact, if true, compacts the returned JSON to minimize transmission bandwidth. Otherwise, the JSON is spaced appropriately for human consumption. Filter allows the caller to provide more specialized filters on the query. Consult the Mailgun documentation for more details.
type Geolocation ¶ added in v1.1.1
type GetEventsOptions ¶
type GetEventsOptions struct {
Begin, End *time.Time
ForceAscending, ForceDescending, Compact bool
Limit int
Filter map[string]string
}
Depreciated See `ListEvents()`
type IP ¶ added in v1.1.1
func (IP) MarshalText ¶ added in v1.1.1
MarshalText satisfies TextMarshaler
func (*IP) UnmarshalText ¶ added in v1.1.1
UnmarshalText satisfies TextUnmarshaler
type List ¶
type List struct { Address string `json:"address,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` AccessLevel string `json:"access_level,omitempty"` CreatedAt string `json:"created_at,omitempty"` MembersCount int `json:"members_count,omitempty"` }
A List structure provides information for a mailing list.
AccessLevel may be one of ReadOnly, Members, or Everyone.
type Mailgun ¶
type Mailgun interface { APIBase() string Domain() string APIKey() string Client() *http.Client SetClient(client *http.Client) Send(m *Message) (string, string, error) GetBounces(limit, skip int) (int, []Bounce, error) GetSingleBounce(address string) (Bounce, error) AddBounce(address, code, error string) error DeleteBounce(address string) error GetStats(limit int, skip int, startDate *time.Time, event ...string) (int, []Stat, error) GetStatsTotal(start *time.Time, end *time.Time, resolution string, duration string, event ...string) (*StatsTotalResponse, error) GetTag(tag string) (TagItem, error) DeleteTag(tag string) error ListTags(*TagOptions) *TagIterator GetDomains(limit, skip int) (int, []Domain, error) GetSingleDomain(domain string) (Domain, []DNSRecord, []DNSRecord, error) CreateDomain(name string, smtpPassword string, spamAction string, wildcard bool) error DeleteDomain(name string) error GetComplaints(limit, skip int) (int, []Complaint, error) GetSingleComplaint(address string) (Complaint, error) GetStoredMessage(id string) (StoredMessage, error) GetStoredMessageRaw(id string) (StoredMessageRaw, error) GetStoredMessageForURL(url string) (StoredMessage, error) GetStoredMessageRawForURL(url string) (StoredMessageRaw, error) DeleteStoredMessage(id string) error GetCredentials(limit, skip int) (int, []Credential, error) CreateCredential(login, password string) error ChangeCredentialPassword(id, password string) error DeleteCredential(id string) error GetUnsubscribes(limit, skip int) (int, []Unsubscription, error) GetUnsubscribesByAddress(string) (int, []Unsubscription, error) Unsubscribe(address, tag string) error RemoveUnsubscribe(string) error RemoveUnsubscribeWithTag(a, t string) error CreateComplaint(string) error DeleteComplaint(string) error GetRoutes(limit, skip int) (int, []Route, error) GetRouteByID(string) (Route, error) CreateRoute(Route) (Route, error) DeleteRoute(string) error UpdateRoute(string, Route) (Route, error) GetWebhooks() (map[string]string, error) CreateWebhook(kind, url string) error DeleteWebhook(kind string) error GetWebhookByType(kind string) (string, error) UpdateWebhook(kind, url string) error VerifyWebhookRequest(req *http.Request) (verified bool, err error) GetLists(limit, skip int, filter string) (int, []List, error) CreateList(List) (List, error) DeleteList(string) error GetListByAddress(string) (List, error) UpdateList(string, List) (List, error) GetMembers(limit, skip int, subfilter *bool, address string) (int, []Member, error) GetMemberByAddress(MemberAddr, listAddr string) (Member, error) CreateMember(merge bool, addr string, prototype Member) error CreateMemberList(subscribed *bool, addr string, newMembers []interface{}) error UpdateMember(Member, list string, prototype Member) (Member, error) DeleteMember(Member, list string) error NewMessage(from, subject, text string, to ...string) *Message NewMIMEMessage(body io.ReadCloser, to ...string) *Message NewEventIterator() *EventIterator ListEvents(*EventsOptions) *EventIterator PollEvents(*EventsOptions) *EventPoller SetAPIBase(url string) }
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 ¶ added in v1.1.0
func NewMailgunFromEnv() (*MailgunImpl, error)
Return a new Mailgun client using the environment variables MG_API_KEY, MG_DOMAIN, and MG_URL
func (*MailgunImpl) APIBase ¶
func (m *MailgunImpl) APIBase() string
ApiBase returns the API Base URL configured for this client.
func (*MailgunImpl) APIKey ¶
func (m *MailgunImpl) APIKey() string
ApiKey returns the API key configured for this client.
func (*MailgunImpl) AddBounce ¶
func (m *MailgunImpl) AddBounce(address, code, error string) error
AddBounce files a bounce report. Address identifies the intended recipient of the message that bounced. Code corresponds to the numeric response given by the e-mail server which rejected the message. Error providees the corresponding human readable reason for the problem. For example, here's how the these two fields relate. Suppose the SMTP server responds with an error, as below. Then, . . .
550 Requested action not taken: mailbox unavailable \___/\_______________________________________________/ | | `-- Code `-- Error
Note that both code and error exist as strings, even though code will report as a number.
func (*MailgunImpl) ChangeCredentialPassword ¶
func (mg *MailgunImpl) ChangeCredentialPassword(id, password string) error
ChangeCredentialPassword attempts to alter the indicated credential's password.
func (*MailgunImpl) Client ¶
func (m *MailgunImpl) Client() *http.Client
Client returns the HTTP client configured for this client.
func (*MailgunImpl) CreateComplaint ¶
func (m *MailgunImpl) CreateComplaint(address string) error
CreateComplaint registers the specified address as a recipient who has complained of receiving spam from your domain.
func (*MailgunImpl) CreateCredential ¶
func (mg *MailgunImpl) CreateCredential(login, password string) error
CreateCredential attempts to create associate a new principle with your domain.
func (*MailgunImpl) CreateDomain ¶
func (m *MailgunImpl) CreateDomain(name string, smtpPassword string, spamAction string, wildcard bool) error
CreateDomain instructs Mailgun to create a new domain for your account. The name parameter identifies the domain. The smtpPassword parameter provides an access credential for the domain. The spamAction domain must be one of Delete, Tag, or Disabled. The wildcard parameter instructs Mailgun to treat all subdomains of this domain uniformly if true, and as different domains if false.
func (*MailgunImpl) CreateList ¶
func (mg *MailgunImpl) CreateList(prototype List) (List, error)
CreateList creates a new mailing list under your Mailgun account. You need specify only the Address and Name members of the prototype; Description, and AccessLevel are optional. If unspecified, Description remains blank, while AccessLevel defaults to Everyone.
func (*MailgunImpl) CreateMember ¶
func (mg *MailgunImpl) CreateMember(merge bool, addr string, prototype Member) error
CreateMember registers a new member of the indicated mailing list. If merge is set to true, then the registration may update an existing Member's settings. Otherwise, an error will occur if you attempt to add a member with a duplicate e-mail address.
func (*MailgunImpl) CreateMemberList ¶
func (mg *MailgunImpl) CreateMemberList(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(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) CreateWebhook ¶
func (mg *MailgunImpl) CreateWebhook(t, u string) error
CreateWebhook installs a new webhook for your domain.
func (*MailgunImpl) DeleteBounce ¶
func (m *MailgunImpl) DeleteBounce(address string) error
DeleteBounce removes all bounces associted with the provided e-mail address.
func (*MailgunImpl) DeleteComplaint ¶
func (m *MailgunImpl) DeleteComplaint(address string) error
DeleteComplaint removes a previously registered e-mail address from the list of people who complained of receiving spam from your domain.
func (*MailgunImpl) DeleteCredential ¶
func (mg *MailgunImpl) DeleteCredential(id string) error
DeleteCredential attempts to remove the indicated principle from the domain.
func (*MailgunImpl) DeleteDomain ¶
func (m *MailgunImpl) DeleteDomain(name string) error
DeleteDomain instructs Mailgun to dispose of the named domain name.
func (*MailgunImpl) DeleteList ¶
func (mg *MailgunImpl) DeleteList(addr string) error
DeleteList removes all current members of the list, then removes the list itself. Attempts to send e-mail to the list will fail subsequent to this call.
func (*MailgunImpl) DeleteMember ¶
func (mg *MailgunImpl) DeleteMember(member, addr string) error
DeleteMember removes the member from the list.
func (*MailgunImpl) DeleteRoute ¶
func (mg *MailgunImpl) DeleteRoute(id string) error
DeleteRoute removes the specified route from your domain's configuration. To avoid ambiguity, Mailgun identifies the route by unique ID. See the Route structure definition and the Mailgun API documentation for more details.
func (*MailgunImpl) DeleteStoredMessage ¶
func (mg *MailgunImpl) DeleteStoredMessage(id string) error
DeleteStoredMessage removes a previously stored message. Note that Mailgun institutes a policy of automatically deleting messages after a set time. Consult the current Mailgun API documentation for more details.
func (*MailgunImpl) DeleteTag ¶
func (m *MailgunImpl) DeleteTag(tag string) error
DeleteTag removes all counters for a particular tag, including the tag itself.
func (*MailgunImpl) DeleteWebhook ¶
func (mg *MailgunImpl) DeleteWebhook(t string) error
DeleteWebhook removes the specified webhook from your domain's configuration.
func (*MailgunImpl) Domain ¶
func (m *MailgunImpl) Domain() string
Domain returns the domain configured for this client.
func (*MailgunImpl) GetBounces ¶
func (m *MailgunImpl) GetBounces(limit, skip int) (int, []Bounce, error)
GetBounces returns a complete set of bounces logged against the sender's domain, if any. The results include the total number of bounces (regardless of skip or limit settings), and the slice of bounces specified, if successful. Note that the length of the slice may be smaller than the total number of bounces.
func (*MailgunImpl) GetComplaints ¶
func (m *MailgunImpl) GetComplaints(limit, skip int) (int, []Complaint, error)
GetComplaints returns a set of spam complaints registered against your domain. Recipients of your messages can click on a link which sends feedback to Mailgun indicating that the message they received is, to them, spam.
func (*MailgunImpl) GetCredentials ¶
func (mg *MailgunImpl) GetCredentials(limit, skip int) (int, []Credential, error)
GetCredentials returns the (possibly zero-length) list of credentials associated with your domain.
func (*MailgunImpl) GetDomains ¶
func (m *MailgunImpl) GetDomains(limit, skip int) (int, []Domain, error)
GetDomains retrieves a set of domains from Mailgun.
Assuming no error, both the number of items retrieved and a slice of Domain instances. The number of items returned may be less than the specified limit, if it's specified. Note that zero items and a zero-length slice do not necessarily imply an error occurred. Except for the error itself, all results are undefined in the event of an error.
func (*MailgunImpl) GetListByAddress ¶
func (mg *MailgunImpl) GetListByAddress(addr string) (List, error)
GetListByAddress allows your application to recover the complete List structure representing a mailing list, so long as you have its e-mail address.
func (*MailgunImpl) GetLists ¶
GetLists returns the specified set of mailing lists administered by your account.
func (*MailgunImpl) GetMemberByAddress ¶
func (mg *MailgunImpl) GetMemberByAddress(s, l string) (Member, error)
GetMemberByAddress returns a complete Member structure for a member of a mailing list, given only their subscription e-mail address.
func (*MailgunImpl) GetMembers ¶
GetMembers returns the list of members belonging to the indicated mailing list. The s parameter can be set to one of three settings to help narrow the returned data set: All indicates that you want both Members and unsubscribed members alike, while Subscribed and Unsubscribed indicate you want only those eponymous subsets.
func (*MailgunImpl) GetRouteByID ¶
func (mg *MailgunImpl) GetRouteByID(id string) (Route, error)
GetRouteByID retrieves the complete route definition associated with the unique route ID.
func (*MailgunImpl) GetRoutes ¶
func (mg *MailgunImpl) GetRoutes(limit, skip int) (int, []Route, error)
GetRoutes returns the complete set of routes configured for your domain. You use routes to configure how to handle returned messages, or messages sent to a specfic address on your domain. See the Mailgun documentation for more information.
Example ¶
mg := NewMailgun("example.com", "my_api_key") n, routes, err := mg.GetRoutes(DefaultLimit, DefaultSkip) if err != nil { log.Fatal(err) } if n > len(routes) { log.Printf("More routes exist than has been returned.") } for _, r := range routes { log.Printf("Route pri=%d expr=%s desc=%s", r.Priority, r.Expression, r.Description) }
Output:
func (*MailgunImpl) GetSingleBounce ¶
func (m *MailgunImpl) GetSingleBounce(address string) (Bounce, error)
GetSingleBounce retrieves a single bounce record, if any exist, for the given recipient address.
func (*MailgunImpl) GetSingleComplaint ¶
func (m *MailgunImpl) GetSingleComplaint(address string) (Complaint, error)
GetSingleComplaint returns a single complaint record filed by a recipient at the email address provided. If no complaint exists, the Complaint instance returned will be empty.
func (*MailgunImpl) GetSingleDomain ¶
Retrieve detailed information about the named domain.
func (*MailgunImpl) GetStats ¶
func (m *MailgunImpl) GetStats(limit int, skip int, startDate *time.Time, event ...string) (int, []Stat, error)
GetStats returns a basic set of statistics for different events. Events start at the given start date, if one is provided. If not, this function will consider all stated events dating to the creation of the sending domain.
func (*MailgunImpl) GetStatsTotal ¶ added in v1.1.1
func (m *MailgunImpl) GetStatsTotal(start *time.Time, end *time.Time, resolution string, duration string, event ...string) (*StatsTotalResponse, error)
GetStatsTotal returns a basic set of statistics for different events. https://documentation.mailgun.com/en/latest/api-stats.html#stats
func (*MailgunImpl) GetStoredMessage ¶
func (mg *MailgunImpl) GetStoredMessage(id string) (StoredMessage, error)
GetStoredMessage retrieves information about a received e-mail message. This provides visibility into, e.g., replies to a message sent to a mailing list.
func (*MailgunImpl) GetStoredMessageForURL ¶ added in v1.1.1
func (mg *MailgunImpl) GetStoredMessageForURL(url string) (StoredMessage, error)
GetStoredMessageForURL retrieves information about a received e-mail message. This provides visibility into, e.g., replies to a message sent to a mailing list.
func (*MailgunImpl) GetStoredMessageRaw ¶
func (mg *MailgunImpl) GetStoredMessageRaw(id string) (StoredMessageRaw, error)
GetStoredMessageRaw retrieves the raw MIME body of a received e-mail message. Compared to GetStoredMessage, it gives access to the unparsed MIME body, and thus delegates to the caller the required parsing.
func (*MailgunImpl) GetStoredMessageRawForURL ¶ added in v1.1.1
func (mg *MailgunImpl) GetStoredMessageRawForURL(url string) (StoredMessageRaw, error)
GetStoredMessageRawForURL 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) GetTag ¶ added in v1.1.0
func (m *MailgunImpl) GetTag(tag string) (TagItem, error)
GetTag retrieves metadata about the tag from the api
func (*MailgunImpl) GetUnsubscribes ¶
func (mg *MailgunImpl) GetUnsubscribes(limit, skip int) (int, []Unsubscription, error)
GetUnsubscribes retrieves a list of unsubscriptions issued by recipients of mail from your domain. Zero is a valid list length.
func (*MailgunImpl) GetUnsubscribesByAddress ¶
func (mg *MailgunImpl) GetUnsubscribesByAddress(a string) (int, []Unsubscription, error)
GetUnsubscribesByAddress retrieves a list of unsubscriptions by recipient address. Zero is a valid list length.
func (*MailgunImpl) GetWebhookByType ¶
func (mg *MailgunImpl) GetWebhookByType(t string) (string, error)
GetWebhookByType retrieves the currently assigned webhook URL associated with the provided type of webhook.
func (*MailgunImpl) GetWebhooks ¶
func (mg *MailgunImpl) GetWebhooks() (map[string]string, error)
GetWebhooks returns the complete set of webhooks configured for your domain. Note that a zero-length mapping is not an error.
func (*MailgunImpl) ListEvents ¶ added in v1.1.0
func (mg *MailgunImpl) ListEvents(opts *EventsOptions) *EventIterator
Create an new iterator to fetch a page of events from the events api
it := mg.ListEvents(EventsOptions{}) var events []Event for it.Next(&events) { for _, event := range events { // Do things with events } } if it.Err() != nil { log.Fatal(it.Err()) }
func (*MailgunImpl) ListTags ¶ added in v1.1.0
func (m *MailgunImpl) ListTags(opts *TagOptions) *TagIterator
ListTags returns a cursor used to iterate through a list of tags
it := mg.ListTags(nil) var page TagsPage for it.Next(&page) { for _, tag := range(page.Items) { // Do stuff with tags } } if it.Err() != nil { log.Fatal(it.Err()) }
func (*MailgunImpl) NewEventIterator ¶
func (mg *MailgunImpl) NewEventIterator() *EventIterator
NewEventIterator creates a new iterator for events. Use GetFirstPage to retrieve the first batch of events. Use GetNext and GetPrevious thereafter as appropriate to iterate through sets of data.
*This call is Deprecated, use ListEvents() instead*
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 ¶ added in v1.1.0
func (mg *MailgunImpl) PollEvents(opts *EventsOptions) *EventPoller
Poll the events api and return new events as they occur
it = mg.PollEvents(&EventsOptions{ // Poll() returns after this threshold is met, or events older than this threshold appear ThresholdAge: time.Second * 10, // 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 // Blocks until new events appear for it.Poll(&events) { for _, event := range(events) { fmt.Printf("Event %+v\n", event) } } if it.Err() != nil { log.Fatal(it.Err()) }
func (*MailgunImpl) RemoveUnsubscribe ¶
func (mg *MailgunImpl) RemoveUnsubscribe(a string) error
RemoveUnsubscribe removes the e-mail address given from the domain's unsubscription table. If passing in an ID (discoverable from, e.g., GetUnsubscribes()), the e-mail address associated with the given ID will be removed.
func (*MailgunImpl) RemoveUnsubscribeWithTag ¶
func (mg *MailgunImpl) RemoveUnsubscribeWithTag(a, t string) error
RemoveUnsubscribe 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., GetUnsubscribes()), the e-mail address associated with the given ID will be removed.
func (*MailgunImpl) Send ¶
func (m *MailgunImpl) Send(message *Message) (mes string, id string, err error)
Send attempts to queue a message (see Message, NewMessage, and its methods) for delivery. It returns the Mailgun server response, which consists of two components: a human-readable status message, and a message ID. The status and message ID are set only if no error occurred.
Example (Constructed) ¶
mg := NewMailgun("example.com", "my_api_key") m := NewMessage( "Excited User <me@example.com>", "Hello World", "Testing some Mailgun Awesomeness!", "baz@example.com", "bar@example.com", ) m.SetTracking(true) m.SetDeliveryTime(time.Now().Add(24 * time.Hour)) m.SetHtml("<html><body><h1>Testing some Mailgun Awesomeness!!</h1></body></html>") _, id, err := mg.Send(m) if err != nil { log.Fatal(err) } log.Printf("Message id=%s", id)
Output:
Example (Mime) ¶
exampleMime := `Content-Type: text/plain; charset="ascii" Subject: Joe's Example Subject From: Joe Example <joe@example.com> To: BARGLEGARF <bargle.garf@example.com> Content-Transfer-Encoding: 7bit Date: Thu, 6 Mar 2014 00:37:52 +0000 Testing some Mailgun MIME awesomeness! ` mg := NewMailgun("example.com", "my_api_key") m := NewMIMEMessage(ioutil.NopCloser(strings.NewReader(exampleMime)), "bargle.garf@example.com") _, id, err := mg.Send(m) if err != nil { log.Fatal(err) } log.Printf("Message id=%s", id)
Output:
func (*MailgunImpl) SetAPIBase ¶ added in v1.1.0
func (m *MailgunImpl) SetAPIBase(address string)
SetAPIBase updates the API Base URL for this client.
func (*MailgunImpl) SetClient ¶
func (m *MailgunImpl) SetClient(c *http.Client)
SetClient updates the HTTP client for this client.
func (*MailgunImpl) Unsubscribe ¶
func (mg *MailgunImpl) Unsubscribe(a, t string) error
Unsubscribe adds an e-mail address to the domain's unsubscription table.
func (*MailgunImpl) UpdateList ¶
func (mg *MailgunImpl) UpdateList(addr string, prototype List) (List, error)
UpdateList allows you to change various attributes of a list. Address, Name, Description, and AccessLevel are all optional; only those fields which are set in the prototype will change.
Be careful! If changing the address of a mailing list, e-mail sent to the old address will not succeed. Make sure you account for the change accordingly.
Example ¶
mg := NewMailgun("example.com", "my_api_key") _, err := mg.UpdateList("joe-stat@example.com", List{ Name: "Joe Stat", Description: "Joe's status report list", }) if err != nil { log.Fatal(err) }
Output:
func (*MailgunImpl) UpdateMember ¶
func (mg *MailgunImpl) UpdateMember(s, l string, prototype Member) (Member, error)
UpdateMember lets you change certain details about the indicated mailing list member. Address, Name, Vars, and Subscribed fields may be changed.
func (*MailgunImpl) UpdateRoute ¶
func (mg *MailgunImpl) UpdateRoute(id string, route Route) (Route, error)
UpdateRoute provides an "in-place" update of the specified route. Only those route fields which are non-zero or non-empty are updated. All other fields remain as-is.
Example ¶
mg := NewMailgun("example.com", "my_api_key") _, err := mg.UpdateRoute("route-id-here", Route{ Priority: 2, }) if err != nil { log.Fatal(err) }
Output:
func (*MailgunImpl) UpdateWebhook ¶
func (mg *MailgunImpl) UpdateWebhook(t, u string) error
UpdateWebhook replaces one webhook setting for another.
func (*MailgunImpl) VerifyWebhookRequest ¶
func (mg *MailgunImpl) VerifyWebhookRequest(req *http.Request) (verified bool, err error)
type MailingList ¶
type MailingListError ¶
type MailingListError struct {
Message string
}
type MailingListMember ¶
type Member ¶
type Member struct { Address string `json:"address,omitempty"` Name string `json:"name,omitempty"` Subscribed *bool `json:"subscribed,omitempty"` Vars map[string]interface{} `json:"vars,omitempty"` }
A Member structure represents a member of the mailing list. The Vars field can represent any JSON-encodable data.
type Message ¶
type Message struct {
// contains filtered or unexported fields
}
Message structures contain both the message text and the envelop for an e-mail message.
func NewMIMEMessage ¶
func NewMIMEMessage(body io.ReadCloser, to ...string) *Message
NewMIMEMessage creates a new MIME message. These messages are largely canned; you do not need to invoke setters to set message-related headers. However, you do still need to call setters for Mailgun-specific settings.
DEPRECATED. The package will panic if you use AddRecipient(), AddBcc(), AddCc(), et. al. on a message already equipped with MaxNumberOfRecipients recipients. Use Mailgun.NewMIMEMessage() instead. It works similarly to this function, but supports larger lists of recipients.
func NewMessage ¶
NewMessage returns a new e-mail message with the simplest envelop needed to send.
DEPRECATED. The package will panic if you use AddRecipient(), AddBcc(), AddCc(), et. al. on a message already equipped with MaxNumberOfRecipients recipients. Use Mailgun.NewMessage() instead. It works similarly to this function, but supports larger lists of recipients.
func (*Message) AddAttachment ¶
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) AddBufferAttachment ¶ added in v1.1.1
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) AddCampaign ¶
This feature is deprecated for new software.
func (*Message) AddDomain ¶ added in v1.1.1
AddDomain allows you to use a separate domain for the type of messages you are sending.
func (*Message) AddInline ¶
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 ¶
AddRecipient appends a receiver to the To: header of a message.
NOTE: Above a certain limit (currently 1000 recipients), this function will cause the message as it's currently defined to be sent. This allows you to support large mailing lists without running into Mailgun's API limitations.
func (*Message) AddRecipientAndVariables ¶
AddRecipientAndVariables appends a receiver to the To: header of a message, and as well attaches a set of variables relevant for this recipient.
NOTE: Above a certain limit (see MaxNumberOfRecipients), this function will cause the message as it's currently defined to be sent. This allows you to support large mailing lists without running into Mailgun's API limitations.
func (*Message) AddTag ¶
AddTag attaches a tag to the message. Tags are useful for metrics gathering and event tracking purposes. Refer to the Mailgun documentation for further details.
func (*Message) AddVariable ¶
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 ¶ added in v1.1.1
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) RecipientCount ¶
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 ¶
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 ¶
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 ¶
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 (*Message) SetTracking ¶
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 ¶
Refer to the Mailgun documentation for more information.
func (*Message) SetTrackingOpens ¶
Refer to the Mailgun documentation for more information.
type Method ¶ added in v1.1.1
type Method uint8
func (Method) MarshalText ¶ added in v1.1.1
MarshalText satisfies TextMarshaler
func (*Method) UnmarshalText ¶ added in v1.1.1
UnmarshalText satisfies TextUnmarshaler
type ReaderAttachment ¶
type ReaderAttachment struct { Filename string ReadCloser io.ReadCloser }
type Recipient ¶ added in v1.1.1
func (Recipient) MarshalText ¶ added in v1.1.1
MarshalText satisfies TextMarshaler
func (*Recipient) UnmarshalText ¶ added in v1.1.1
UnmarshalText satisfies TextUnmarshaler
type Route ¶
type Route struct { Priority int `json:"priority,omitempty"` Description string `json:"description,omitempty"` Expression string `json:"expression,omitempty"` Actions []string `json:"actions,omitempty"` CreatedAt string `json:"created_at,omitempty"` ID string `json:"id,omitempty"` }
A Route structure contains information on a configured or to-be-configured route. The Priority field indicates how soon the route works relative to other configured routes. Routes of equal priority are consulted in chronological order. The Description field provides a human-readable description for the route. Mailgun ignores this field except to provide the description when viewing the Mailgun web control panel. The Expression field lets you specify a pattern to match incoming messages against. The Actions field contains strings specifying what to do with any message which matches the provided expression. The CreatedAt field provides a time-stamp for when the route came into existence. Finally, the ID field provides a unique identifier for this route.
When creating a new route, the SDK only uses a subset of the fields of this structure. In particular, CreatedAt and ID are meaningless in this context, and will be ignored. Only Priority, Description, Expression, and Actions need be provided.
type StatsTotal ¶ added in v1.1.1
type StatsTotal 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"` }
type StatsTotalResponse ¶ added in v1.1.1
type StatsTotalResponse struct { End string `json:"end"` Resolution string `json:"resolution"` Start string `json:"start"` Stats []StatsTotal `json:"stats"` }
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 TagIterator ¶ added in v1.1.0
type TagIterator struct {
// contains filtered or unexported fields
}
func NewTagCursor ¶ added in v1.1.0
func NewTagCursor(tagPage TagsPage, mailgun Mailgun) *TagIterator
Creates a new cursor from a taglist
func (*TagIterator) Err ¶ added in v1.1.0
func (t *TagIterator) Err() error
Return any error if one occurred
func (*TagIterator) First ¶ added in v1.1.0
func (t *TagIterator) First(tagPage *TagsPage) bool
Returns the first page in the list of tags
func (*TagIterator) Last ¶ added in v1.1.0
func (t *TagIterator) Last(tagPage *TagsPage) bool
Returns the last page in the list of tags
func (*TagIterator) Next ¶ added in v1.1.0
func (t *TagIterator) Next(tagPage *TagsPage) bool
Returns the next page in the list of tags
func (*TagIterator) Previous ¶ added in v1.1.0
func (t *TagIterator) Previous(tagPage *TagsPage) bool
Returns the previous page in the list of tags
type TagOptions ¶ added in v1.1.0
type TagOptions struct { // Restrict the page size to this limit Limit int // Return only the tags starting with the given prefix Prefix string // The page direction based off the 'tag' parameter; valid choices are (first, last, next, prev) Page string // The tag that marks piviot point for the 'page' parameter Tag string }
type TimestampNano ¶ added in v1.1.1
func (TimestampNano) MarshalJSON ¶ added in v1.1.1
func (tn TimestampNano) MarshalJSON() ([]byte, error)
MarshalText satisfies JSONMarshaler
func (*TimestampNano) UnmarshalJSON ¶ added in v1.1.1
func (tn *TimestampNano) UnmarshalJSON(data []byte) error
UnmarshalText satisfies JSONUnmarshaler
type TransportMethod ¶ added in v1.1.1
type TransportMethod uint
const ( TransportUnknown TransportMethod = iota TransportHTTP TransportSMTP )
func (TransportMethod) MarshalText ¶ added in v1.1.1
func (tm TransportMethod) MarshalText() ([]byte, error)
MarshalText satisfies TextMarshaler
func (TransportMethod) String ¶ added in v1.1.1
func (tm TransportMethod) String() string
func (*TransportMethod) UnmarshalText ¶ added in v1.1.1
func (tm *TransportMethod) UnmarshalText(text []byte) error
UnmarshalText satisfies TextUnmarshaler
type UnexpectedResponseError ¶
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.