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 ¶
- Constants
- Variables
- func GetStatusFromErr(err error) int
- func TimeToFloat(t time.Time) float64
- type Accepted
- type AccessLevel
- type Bounce
- type BouncesIterator
- func (ci *BouncesIterator) Err() error
- func (ci *BouncesIterator) First(ctx context.Context, items *[]Bounce) bool
- func (ci *BouncesIterator) Last(ctx context.Context, items *[]Bounce) bool
- func (ci *BouncesIterator) Next(ctx context.Context, items *[]Bounce) bool
- func (ci *BouncesIterator) Previous(ctx context.Context, items *[]Bounce) bool
- type BufferAttachment
- type Complaint
- type ComplaintsIterator
- func (ci *ComplaintsIterator) Err() error
- func (ci *ComplaintsIterator) First(ctx context.Context, items *[]Complaint) bool
- func (ci *ComplaintsIterator) Last(ctx context.Context, items *[]Complaint) bool
- func (ci *ComplaintsIterator) Next(ctx context.Context, items *[]Complaint) bool
- func (ci *ComplaintsIterator) Previous(ctx context.Context, items *[]Complaint) bool
- type CreateDomainOptions
- type Credential
- type CredentialsIterator
- func (ri *CredentialsIterator) Err() error
- func (ri *CredentialsIterator) First(ctx context.Context, items *[]Credential) bool
- func (ri *CredentialsIterator) Last(ctx context.Context, items *[]Credential) bool
- func (ri *CredentialsIterator) Next(ctx context.Context, items *[]Credential) bool
- func (ri *CredentialsIterator) Offset() int
- func (ri *CredentialsIterator) Previous(ctx context.Context, items *[]Credential) bool
- type DNSRecord
- type Delivered
- type Domain
- type DomainConnection
- type DomainContainer
- type DomainResponse
- type DomainTracking
- type DomainsIterator
- func (ri *DomainsIterator) Err() error
- func (ri *DomainsIterator) First(ctx context.Context, items *[]Domain) bool
- func (ri *DomainsIterator) Last(ctx context.Context, items *[]Domain) bool
- func (ri *DomainsIterator) Next(ctx context.Context, items *[]Domain) bool
- func (ri *DomainsIterator) Offset() int
- func (ri *DomainsIterator) Previous(ctx context.Context, items *[]Domain) bool
- type EmailValidator
- type EmailValidatorImpl
- func (m *EmailValidatorImpl) APIBase() string
- func (m *EmailValidatorImpl) APIKey() string
- func (m *EmailValidatorImpl) Client() *http.Client
- func (m *EmailValidatorImpl) ParseAddresses(ctx context.Context, addresses ...string) ([]string, []string, error)
- func (m *EmailValidatorImpl) SetAPIBase(address string)
- func (m *EmailValidatorImpl) SetClient(c *http.Client)
- func (m *EmailValidatorImpl) ValidateEmail(ctx context.Context, email string, mailBoxVerify bool) (EmailVerification, error)
- type EmailVerification
- type EmailVerificationParts
- type Event
- type EventIterator
- func (ei *EventIterator) Err() error
- func (ei *EventIterator) First(ctx context.Context, events *[]Event) bool
- func (ei *EventIterator) Last(ctx context.Context, events *[]Event) bool
- func (ei *EventIterator) Next(ctx context.Context, events *[]Event) bool
- func (ei *EventIterator) Previous(ctx context.Context, events *[]Event) bool
- type EventPoller
- type Export
- type ExportList
- type Failed
- type GetStatOptions
- type IPAddress
- type ListEventOptions
- type ListOptions
- type ListTagOptions
- type ListTemplateOptions
- type ListsIterator
- func (li *ListsIterator) Err() error
- func (li *ListsIterator) First(ctx context.Context, items *[]MailingList) bool
- func (li *ListsIterator) Last(ctx context.Context, items *[]MailingList) bool
- func (li *ListsIterator) Next(ctx context.Context, items *[]MailingList) bool
- func (li *ListsIterator) Previous(ctx context.Context, items *[]MailingList) bool
- type Mailgun
- type MailgunImpl
- func (mg *MailgunImpl) APIBase() string
- func (mg *MailgunImpl) APIKey() string
- func (mg *MailgunImpl) AddBounce(ctx context.Context, address, code, error string) error
- func (mg *MailgunImpl) AddDomainIP(ctx context.Context, ip string) error
- func (mg *MailgunImpl) AddTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error
- func (mg *MailgunImpl) ChangeCredentialPassword(ctx context.Context, login, password string) error
- func (mg *MailgunImpl) Client() *http.Client
- func (mg *MailgunImpl) CreateComplaint(ctx context.Context, address string) error
- func (mg *MailgunImpl) CreateCredential(ctx context.Context, login, password string) error
- func (mg *MailgunImpl) CreateDomain(ctx context.Context, name string, opts *CreateDomainOptions) (DomainResponse, error)
- func (mg *MailgunImpl) CreateExport(ctx context.Context, url string) error
- func (mg *MailgunImpl) CreateMailingList(ctx context.Context, prototype MailingList) (MailingList, error)
- func (mg *MailgunImpl) CreateMember(ctx context.Context, merge bool, addr string, prototype Member) error
- func (mg *MailgunImpl) CreateMemberList(ctx context.Context, u *bool, addr string, newMembers []interface{}) error
- func (mg *MailgunImpl) CreateRoute(ctx context.Context, prototype Route) (_ignored Route, err error)
- func (mg *MailgunImpl) CreateTemplate(ctx context.Context, template *Template) error
- func (mg *MailgunImpl) CreateUnsubscribe(ctx context.Context, address, tag string) error
- func (mg *MailgunImpl) CreateUnsubscribes(ctx context.Context, unsubscribes []Unsubscribe) error
- func (mg *MailgunImpl) CreateWebhook(ctx context.Context, kind string, urls []string) error
- func (mg *MailgunImpl) DeleteBounce(ctx context.Context, address string) error
- func (mg *MailgunImpl) DeleteBounceList(ctx context.Context) error
- func (mg *MailgunImpl) DeleteComplaint(ctx context.Context, address string) error
- func (mg *MailgunImpl) DeleteCredential(ctx context.Context, login string) error
- func (mg *MailgunImpl) DeleteDomain(ctx context.Context, name string) error
- func (mg *MailgunImpl) DeleteDomainIP(ctx context.Context, ip string) error
- func (mg *MailgunImpl) DeleteMailingList(ctx context.Context, addr string) error
- func (mg *MailgunImpl) DeleteMember(ctx context.Context, member, addr string) error
- func (mg *MailgunImpl) DeleteRoute(ctx context.Context, id string) error
- func (mg *MailgunImpl) DeleteTag(ctx context.Context, tag string) error
- func (mg *MailgunImpl) DeleteTemplate(ctx context.Context, name string) error
- func (mg *MailgunImpl) DeleteTemplateVersion(ctx context.Context, templateName, tag string) error
- func (mg *MailgunImpl) DeleteUnsubscribe(ctx context.Context, address string) error
- func (mg *MailgunImpl) DeleteUnsubscribeWithTag(ctx context.Context, a, t string) error
- func (mg *MailgunImpl) DeleteWebhook(ctx context.Context, kind string) error
- func (mg *MailgunImpl) Domain() string
- func (mg *MailgunImpl) GetBounce(ctx context.Context, address string) (Bounce, error)
- func (mg *MailgunImpl) GetComplaint(ctx context.Context, address string) (Complaint, error)
- func (mg *MailgunImpl) GetDomain(ctx context.Context, domain string) (DomainResponse, error)
- func (mg *MailgunImpl) GetDomainConnection(ctx context.Context, domain string) (DomainConnection, error)
- func (mg *MailgunImpl) GetDomainTracking(ctx context.Context, domain string) (DomainTracking, error)
- func (mg *MailgunImpl) GetExport(ctx context.Context, id string) (Export, error)
- func (mg *MailgunImpl) GetExportLink(ctx context.Context, id string) (string, error)
- func (mg *MailgunImpl) GetIP(ctx context.Context, ip string) (IPAddress, error)
- func (mg *MailgunImpl) GetMailingList(ctx context.Context, addr string) (MailingList, error)
- func (mg *MailgunImpl) GetMember(ctx context.Context, s, l string) (Member, error)
- func (mg *MailgunImpl) GetRoute(ctx context.Context, id string) (Route, error)
- func (mg *MailgunImpl) GetStats(ctx context.Context, events []string, opts *GetStatOptions) ([]Stats, error)
- func (mg *MailgunImpl) GetStoredAttachment(ctx context.Context, url string) ([]byte, error)
- func (mg *MailgunImpl) GetStoredMessage(ctx context.Context, url string) (StoredMessage, error)
- func (mg *MailgunImpl) GetStoredMessageForURL(ctx context.Context, url string) (StoredMessage, error)deprecated
- func (mg *MailgunImpl) GetStoredMessageRaw(ctx context.Context, url string) (StoredMessageRaw, error)
- func (mg *MailgunImpl) GetStoredMessageRawForURL(ctx context.Context, url string) (StoredMessageRaw, error)deprecated
- func (mg *MailgunImpl) GetTag(ctx context.Context, tag string) (Tag, error)
- func (mg *MailgunImpl) GetTagLimits(ctx context.Context, domain string) (TagLimits, error)
- func (mg *MailgunImpl) GetTemplate(ctx context.Context, name string) (Template, error)
- func (mg *MailgunImpl) GetTemplateVersion(ctx context.Context, templateName, tag string) (TemplateVersion, error)
- func (mg *MailgunImpl) GetUnsubscribe(ctx context.Context, address string) (Unsubscribe, error)
- func (mg *MailgunImpl) GetWebhook(ctx context.Context, kind string) ([]string, error)
- func (mg *MailgunImpl) ListBounces(opts *ListOptions) *BouncesIterator
- func (mg *MailgunImpl) ListComplaints(opts *ListOptions) *ComplaintsIterator
- func (mg *MailgunImpl) ListCredentials(opts *ListOptions) *CredentialsIterator
- func (mg *MailgunImpl) ListDomainIPS(ctx context.Context) ([]IPAddress, error)
- func (mg *MailgunImpl) ListDomains(opts *ListOptions) *DomainsIterator
- func (mg *MailgunImpl) ListEvents(opts *ListEventOptions) *EventIterator
- func (mg *MailgunImpl) ListEventsWithDomain(opts *ListEventOptions, domain string) *EventIterator
- func (mg *MailgunImpl) ListExports(ctx context.Context, url string) ([]Export, error)
- func (mg *MailgunImpl) ListIPS(ctx context.Context, dedicated bool) ([]IPAddress, error)
- func (mg *MailgunImpl) ListMailingLists(opts *ListOptions) *ListsIterator
- func (mg *MailgunImpl) ListMembers(address string, opts *ListOptions) *MemberListIterator
- func (mg *MailgunImpl) ListRoutes(opts *ListOptions) *RoutesIterator
- func (mg *MailgunImpl) ListTags(opts *ListTagOptions) *TagIterator
- func (mg *MailgunImpl) ListTemplateVersions(templateName string, opts *ListOptions) *TemplateVersionsIterator
- func (mg *MailgunImpl) ListTemplates(opts *ListTemplateOptions) *TemplatesIterator
- func (mg *MailgunImpl) ListUnsubscribes(opts *ListOptions) *UnsubscribesIterator
- func (mg *MailgunImpl) ListWebhooks(ctx context.Context) (map[string][]string, error)
- 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 *ListEventOptions) *EventPoller
- func (mg *MailgunImpl) ReSend(ctx context.Context, url string, recipients ...string) (string, string, error)
- func (mg *MailgunImpl) Send(ctx context.Context, message *Message) (mes string, id string, err error)
- func (mg *MailgunImpl) SetAPIBase(address string)
- func (mg *MailgunImpl) SetClient(c *http.Client)
- func (mg *MailgunImpl) UpdateClickTracking(ctx context.Context, domain, active string) error
- func (mg *MailgunImpl) UpdateDomainConnection(ctx context.Context, domain string, settings DomainConnection) error
- func (mg *MailgunImpl) UpdateDomainDkimSelector(ctx context.Context, domain, dkimSelector string) error
- func (mg *MailgunImpl) UpdateDomainTrackingWebPrefix(ctx context.Context, domain, webPrefix string) error
- func (mg *MailgunImpl) UpdateMailingList(ctx context.Context, addr string, prototype MailingList) (MailingList, error)
- func (mg *MailgunImpl) UpdateMember(ctx context.Context, s, l string, prototype Member) (Member, error)
- func (mg *MailgunImpl) UpdateOpenTracking(ctx context.Context, domain, active string) error
- func (mg *MailgunImpl) UpdateRoute(ctx context.Context, id string, route Route) (Route, error)
- func (mg *MailgunImpl) UpdateTemplate(ctx context.Context, template *Template) error
- func (mg *MailgunImpl) UpdateTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error
- func (mg *MailgunImpl) UpdateUnsubscribeTracking(ctx context.Context, domain, active, htmlFooter, textFooter string) error
- func (mg *MailgunImpl) UpdateWebhook(ctx context.Context, kind string, urls []string) error
- func (mg *MailgunImpl) VerifyAndReturnDomain(ctx context.Context, domain string) (DomainResponse, error)
- func (mg *MailgunImpl) VerifyDomain(ctx context.Context, domain string) (string, error)
- func (mg *MailgunImpl) VerifyWebhookRequest(req *http.Request) (verified bool, err error)deprecated
- func (mg *MailgunImpl) VerifyWebhookSignature(sig Signature) (verified bool, err error)
- type MailingList
- type MailingListContainer
- type Member
- type MemberListIterator
- func (li *MemberListIterator) Err() error
- func (li *MemberListIterator) First(ctx context.Context, items *[]Member) bool
- func (li *MemberListIterator) Last(ctx context.Context, items *[]Member) bool
- func (li *MemberListIterator) Next(ctx context.Context, items *[]Member) bool
- func (li *MemberListIterator) Previous(ctx context.Context, items *[]Member) bool
- 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) error
- func (m *Message) AddTemplateVariable(variable string, value interface{}) error
- func (m *Message) AddVariable(variable string, value interface{}) error
- func (m *Message) EnableNativeSend()
- func (m *Message) EnableTestMode()
- func (m *Message) GetHeaders() map[string]string
- func (m *Message) RecipientCount() int
- func (m *Message) SetAMPHtml(html string)
- 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) SetRequireTLS(b bool)
- func (m *Message) SetSkipVerification(b bool)
- func (m *Message) SetTemplate(t string)
- func (m *Message) SetTemplateRenderText(render bool)
- func (m *Message) SetTemplateVersion(tag string)
- func (m *Message) SetTracking(tracking bool)
- func (m *Message) SetTrackingClicks(trackingClicks bool)
- func (m *Message) SetTrackingOpens(trackingOpens bool)
- func (m *Message) SetTrackingOptions(options *TrackingOptions)
- type MockServer
- type Paging
- type Permanent
- type RFC2822Time
- type ReaderAttachment
- type Recipient
- type Resolution
- type Route
- type RoutesIterator
- func (ri *RoutesIterator) Err() error
- func (ri *RoutesIterator) First(ctx context.Context, items *[]Route) bool
- func (ri *RoutesIterator) Last(ctx context.Context, items *[]Route) bool
- func (ri *RoutesIterator) Next(ctx context.Context, items *[]Route) bool
- func (ri *RoutesIterator) Offset() int
- func (ri *RoutesIterator) Previous(ctx context.Context, items *[]Route) bool
- type Signature
- type SpamAction
- type Stats
- type StoredAttachment
- type StoredMessage
- type StoredMessageRaw
- type Tag
- type TagIterator
- func (ti *TagIterator) Err() error
- func (ti *TagIterator) First(ctx context.Context, items *[]Tag) bool
- func (ti *TagIterator) Last(ctx context.Context, items *[]Tag) bool
- func (ti *TagIterator) Next(ctx context.Context, items *[]Tag) bool
- func (ti *TagIterator) Previous(ctx context.Context, items *[]Tag) bool
- type TagLimits
- type Template
- type TemplateEngine
- type TemplateVersion
- type TemplateVersionsIterator
- func (li *TemplateVersionsIterator) Err() error
- func (li *TemplateVersionsIterator) First(ctx context.Context, items *[]TemplateVersion) bool
- func (li *TemplateVersionsIterator) Last(ctx context.Context, items *[]TemplateVersion) bool
- func (li *TemplateVersionsIterator) Next(ctx context.Context, items *[]TemplateVersion) bool
- func (li *TemplateVersionsIterator) Previous(ctx context.Context, items *[]TemplateVersion) bool
- type TemplatesIterator
- func (ti *TemplatesIterator) Err() error
- func (ti *TemplatesIterator) First(ctx context.Context, items *[]Template) bool
- func (ti *TemplatesIterator) Last(ctx context.Context, items *[]Template) bool
- func (ti *TemplatesIterator) Next(ctx context.Context, items *[]Template) bool
- func (ti *TemplatesIterator) Previous(ctx context.Context, items *[]Template) bool
- type Temporary
- type Total
- type TrackingOptions
- type TrackingStatus
- type UnexpectedResponseError
- type Unsubscribe
- type UnsubscribesIterator
- func (ci *UnsubscribesIterator) Err() error
- func (ci *UnsubscribesIterator) First(ctx context.Context, items *[]Unsubscribe) bool
- func (ci *UnsubscribesIterator) Last(ctx context.Context, items *[]Unsubscribe) bool
- func (ci *UnsubscribesIterator) Next(ctx context.Context, items *[]Unsubscribe) bool
- func (ci *UnsubscribesIterator) Previous(ctx context.Context, items *[]Unsubscribe) bool
- type UrlOrUrls
- type WebHookResponse
- type WebHooksListResponse
- type WebhookPayload
Examples ¶
Constants ¶
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.
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" )
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.
const ( ResolutionHour = Resolution("hour") ResolutionDay = Resolution("day") ResolutionMonth = Resolution("month") )
Indicate which resolution a stat response for request is for
const ( TemplateEngineHandlebars = TemplateEngine("handlebars") TemplateEngineGo = TemplateEngine("go") )
Used by CreateTemplate() and AddTemplateVersion() to specify the template engine
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.
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.
const MaxNumberOfTags = 3
MaxNumberOfTags represents the maximum number of tags that can be added for a message
const Version = "4.5.1"
Version of current release
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
Set true to write the HTTP requests in curl for to stdout
var ErrEmptyParam = fmt.Errorf("empty or illegal parameter")
Returned when a required parameter is missing.
var ErrInvalidMessage = errors.New("message not valid")
ErrInvalidMessage is returned by `Send()` when the `mailgun.Message` struct is incomplete
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 ¶
Extract the http status code from error object
func TimeToFloat ¶
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 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.
type BufferAttachment ¶
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 WebScheme 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 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"` WebScheme string `json:"web_scheme"` }
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 DomainContainer ¶
type DomainContainer struct { Domain Domain `json:"domain"` ReceivingDNSRecords []DNSRecord `json:"receiving_dns_records"` SendingDNSRecords []DNSRecord `json:"sending_dns_records"` Connection *DomainConnection `json:"connection,omitempty"` Tracking *DomainTracking `json:"tracking,omitempty"` TagLimits *TagLimits `json:"limits,omitempty"` }
type DomainResponse ¶
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
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)
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. If user has set the
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"` // The reason why a specific validation may be unsuccessful. (Available in the V3 response) Reason string `json:"reason"` // A list of potential reasons why a specific validation may be unsuccessful. (Available in the v4 response) Reasons []string // Risk assessment for the provided email. Risk string `json:"risk"` // Result Result string `json:"result"` }
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 { 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 ¶
Parse converts raw bytes data into an event struct. Can accept events.RawJSON as input
type EventIterator ¶
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.
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
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 ¶
Options for GetStats()
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 ListTemplateOptions ¶
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 DeleteBounceList(ctx context.Context) 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 CreateUnsubscribes(ctx context.Context, unsubscribes []Unsubscribe) 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 ListEventsWithDomain(opts *ListEventOptions, domain string) *EventIterator 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 provides 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) CreateUnsubscribes ¶
func (mg *MailgunImpl) CreateUnsubscribes(ctx context.Context, unsubscribes []Unsubscribe) error
CreateUnsubscribes adds multiple e-mail addresses to the domain's unsubscription table.
func (*MailgunImpl) CreateWebhook ¶
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) DeleteBounceList ¶
func (mg *MailgunImpl) DeleteBounceList(ctx context.Context) error
DeleteBounceList removes all bounces in the bounce list
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 ¶
GetBounce retrieves a single bounce record, if any exist, for the given recipient address.
func (*MailgunImpl) GetComplaint ¶
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) GetExportLink ¶
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) 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 ¶
GetMember returns a complete Member structure for a member of a mailing list, given only their subscription e-mail address.
func (*MailgunImpl) GetRoute ¶
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 ¶
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) GetTagLimits ¶
GetTagLimits returns tracking settings for a domain
func (*MailgunImpl) GetTemplate ¶
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 ¶
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) ListEventsWithDomain ¶
func (mg *MailgunImpl) ListEventsWithDomain(opts *ListEventOptions, domain string) *EventIterator
Create an new iterator to fetch a page of events from the events api with a specific domain
func (*MailgunImpl) ListExports ¶
List all exports created within the past 24 hours
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 ¶
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 ¶
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 ¶
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) UpdateDomainDkimSelector ¶
func (mg *MailgunImpl) UpdateDomainDkimSelector(ctx context.Context, domain, dkimSelector string) error
Update the DKIM selector for a domain
func (*MailgunImpl) UpdateDomainTrackingWebPrefix ¶
func (mg *MailgunImpl) UpdateDomainTrackingWebPrefix(ctx context.Context, domain, webPrefix string) error
Update the CNAME used for tracking opens and clicks
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 ¶
func (mg *MailgunImpl) UpdateOpenTracking(ctx context.Context, domain, active string) error
func (*MailgunImpl) UpdateRoute ¶
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 ¶
func (mg *MailgunImpl) UpdateUnsubscribeTracking(ctx context.Context, domain, active, htmlFooter, textFooter string) error
func (*MailgunImpl) UpdateWebhook ¶
UpdateWebhook replaces one webhook setting for another.
func (*MailgunImpl) VerifyAndReturnDomain ¶
func (mg *MailgunImpl) VerifyAndReturnDomain(ctx context.Context, domain string) (DomainResponse, error)
VerifyAndReturnDomain verifies & retrieves detailed information about the named domain.
func (*MailgunImpl) VerifyDomain ¶
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 ¶
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 MailingListContainer ¶
type MailingListContainer struct { MailingList MailingList Members []Member }
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.
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 ¶
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 ¶
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 ¶
AddCampaign is no longer supported and is deprecated for new software.
func (*Message) AddDomain ¶
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. It will return an error if the limit of recipients have been exceeded for this message
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. It will return an error if the limit of recipients have been exceeded for this message
func (*Message) AddTag ¶
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 ¶
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 ¶
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 ¶
GetHeaders retrieves the http headers associated with this message
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) SetAMPHtml ¶
SetAMP is a helper. If you're sending a message that isn't already MIME encoded, SetAMP() will arrange to bundle an AMP-For-Email representation of your message in addition to your html & plain-text content.
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 ¶
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 ¶
SetReplyTo sets the receiver who should receive replies
func (*Message) SetRequireTLS ¶
SetRequireTLS information is found in the Mailgun documentation.
func (*Message) SetSkipVerification ¶
SetSkipVerification information is found in the Mailgun documentation.
func (*Message) SetTemplate ¶
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) SetTemplateRenderText ¶
SetTemplateRenderText information is found in the Mailgun documentation.
func (*Message) SetTemplateVersion ¶
SetTemplateVersion information is found in the Mailgun documentation.
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 ¶
SetTrackingClicks information is found in the Mailgun documentation.
func (*Message) SetTrackingOpens ¶
SetTrackingOpens information is found in the Mailgun documentation.
func (*Message) SetTrackingOptions ¶
func (m *Message) SetTrackingOptions(options *TrackingOptions)
SetTrackingOptions sets the o:tracking, o:tracking-clicks and o:tracking-opens at once.
type MockServer ¶
type MockServer interface { Stop() URL4() string URL() string DomainIPS() []string DomainList() []DomainContainer ExportList() []Export MailingList() []MailingListContainer RouteList() []Route Events() []Event Webhooks() WebHooksListResponse }
func NewMockServer ¶
func NewMockServer() MockServer
Create a new instance of the mailgun API mock server
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 ¶
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 ¶
func (Recipient) MarshalText ¶
MarshalText satisfies TextMarshaler
func (*Recipient) UnmarshalText ¶
UnmarshalText satisfies TextUnmarshaler
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
type Signature ¶
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 TagIterator ¶
type TagIterator struct {
// contains filtered or unexported fields
}
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
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 ¶
func (li *TemplateVersionsIterator) Last(ctx context.Context, items *[]TemplateVersion) 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 (*TemplateVersionsIterator) Next ¶
func (li *TemplateVersionsIterator) Next(ctx context.Context, items *[]TemplateVersion) 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 (*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.
type Temporary ¶
type Temporary struct {
Espblock int `json:"espblock"`
}
Stats on temporary failures
type TrackingOptions ¶
TrackingOptions contains fields relevant to trackings.
type TrackingStatus ¶
type TrackingStatus struct { Active bool `json:"active"` }
The tracking status of a domain
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.
type Unsubscribe ¶
type Unsubscribe struct { CreatedAt RFC2822Time `json:"created_at,omitempty"` Tags []string `json:"tags,omitempty"` ID string `json:"id,omitempty"` 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 WebHookResponse ¶
type WebHookResponse struct {
Webhook UrlOrUrls `json:"webhook"`
}
type WebHooksListResponse ¶
type WebhookPayload ¶
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
Source Files ¶
- bounces.go
- credentials.go
- domains.go
- email_validation.go
- events.go
- exports.go
- httphelpers.go
- ips.go
- limits.go
- mailgun.go
- mailing_lists.go
- members.go
- messages.go
- mock.go
- mock_domains.go
- mock_events.go
- mock_exports.go
- mock_ips.go
- mock_mailing_list.go
- mock_messages.go
- mock_routes.go
- mock_validation.go
- mock_webhooks.go
- parse.go
- recipients.go
- rest_shim.go
- rfc2822.go
- routes.go
- spam_complaints.go
- stats.go
- tags.go
- template.go
- template_versions.go
- unsubscribes.go
- version.go
- webhooks.go