Categorygithub.com/yjimk/mailgun-go/v4
modulepackage
4.3.6
Repository: https://github.com/yjimk/mailgun-go.git
Documentation: pkg.go.dev

# README

Mailgun with Go

GoDoc Build Status

Go library for interacting with the Mailgun API.

Usage

package main

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

    "github.com/yjimk/mailgun-go/v4"
)

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

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


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

    sender := "[email protected]"
    subject := "Fancy subject!"
    body := "Hello from Mailgun Go!"
    recipient := "[email protected]"

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

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

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

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

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

Get Events

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/yjimk/mailgun-go/v4"
    "github.com/yjimk/mailgun-go/v4/events"
)

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

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

    var page []mailgun.Event

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

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

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

Event Polling

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

package main

import (
    "context"
    "time"

    "github.com/yjimk/mailgun-go/v4"
)

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

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

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

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

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

Email Validations

package main

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

    "github.com/yjimk/mailgun-go/v4"
)

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

func main() {
    // To use the /v4 version of validations define MG_URL in the environment
    // as `https://api.mailgun.net/v4` or set `v.SetAPIBase("https://api.mailgun.net/v4")`

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

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

    email, err := v.ValidateEmail(ctx, "[email protected]", false)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Valid: %t\n", email.IsValid)
}

Webhook Handling

package main

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

    "github.com/yjimk/mailgun-go/v4"
    "github.com/yjimk/mailgun-go/v4/events"
)

func main() {

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

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

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

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

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

        fmt.Printf("Verified Signature\n")

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

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

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

Using Templates

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

package main

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

    "github.com/yjimk/mailgun-go/v4"
)

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

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


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

    sender := "[email protected]"
    subject := "Fancy subject!"
    body := ""
    recipient := "[email protected]"

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

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

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

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

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

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

EU Region

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

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

Installation

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

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

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

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

NOTE for go dep users

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

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

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

Testing

WARNING - running the tests will cost you money!

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

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

and finally

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

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

# Packages

No description provided by the author
No description provided by the author

# Functions

Extract the http status code from error object.
Creates a new validation instance.
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.
NewMailGun creates a new client instance.
NewMailgunFromEnv returns a new Mailgun client using the environment variables MG_API_KEY, MG_DOMAIN, and MG_URL.
Create a new instance of the mailgun API mock server.
No description provided by the author
Parse converts raw bytes data into an event struct.
Given a slice of events.RawJSON events return a slice of Event for each parsed event.
Given time.Time{} return a float64 as given in mailgun event timestamps.

# Constants

Everyone specifies that anyone and everyone may both read and submit messages to the mailing list, including non-subscribers.
Members specifies that only those who subscribe to the mailing list may send messages.
ReadOnly specifies that nobody, including Members, may send messages to the mailing list.
Base Url the library uses to contact mailgun.
No description provided by the author
No description provided by the author
The MailgunGoUserAgent identifies the client to the server, for logging purposes.
MaxNumberOfRecipients represents the largest batch of recipients that Mailgun can support in a single API call.
MaxNumberOfTags represents the maximum number of tags that can be added for a message.
Indicate which resolution a stat response for request is for.
Indicate which resolution a stat response for request is for.
Indicate which resolution a stat response for request is for.
instructs Mailgun to just block or delete the message all-together.
Prevents Mailgun from taking any action on what it perceives to be spam.
Tag the received message with headers providing a measure of its spamness.
Used by CreateTemplate() and AddTemplateVersion() to specify the template engine.
Used by CreateTemplate() and AddTemplateVersion() to specify the template engine.
Version of current release.

# Variables

Mailing list members have an attribute that determines if they've subscribed to the mailing list or not.
Set true to write the HTTP requests in curl for to stdout.
Returned when a required parameter is missing.
ErrInvalidMessage is returned by `Send()` when the `mailgun.Message` struct is incomplete.
A list of all JSON event types returned by the /events API.
Mailing list members have an attribute that determines if they've subscribed to the mailing list or not.
Mailing list members have an attribute that determines if they've subscribed to the mailing list or not.

# Structs

Stats on accepted messages.
Bounce aggregates data relating to undeliverable messages to a specific intended recipient, identified by Address.
No description provided by the author
No description provided by the author
Complaint structures track how many times one of your emails have been marked as spam.
No description provided by the author
Optional parameters when creating a domain.
A Credential structure describes a principle allowed to send or receive mail at the domain.
No description provided by the author
Stats on delivered messages.
DNSRecord structures describe intended records to properly configure your domain for use with Mailgun.
A Domain structure holds information about a domain used when sending mail.
Specify the domain connection options.
No description provided by the author
No description provided by the author
Specify the domain tracking options.
No description provided by the author
EmailVerification records basic facts about a validated e-mail address.
The EmailVerificationParts structure breaks out the basic elements of an email address.
EventIterator maintains the state necessary for paging though small parcels of a larger set of events.
EventPoller maintains the state necessary for polling events.
No description provided by the author
No description provided by the author
Stats on failed messages.
Options for GetStats().
No description provided by the author
ListEventOptions{} modifies the behavior of ListEvents().
Used by List methods to specify what list parameters to send to the mailgun API.
No description provided by the author
No description provided by the author
No description provided by the author
MailgunImpl bundles data needed by a large number of methods in order to interact with the Mailgun API.
A List structure provides information for a mailing list.
A Member structure represents a member of the mailing list.
No description provided by the author
Message structures contain both the message text and the envelop for an e-mail message.
A mailgun api mock suitable for testing.
No description provided by the author
Stats on permanent failures.
No description provided by the author
No description provided by the author
A Route structure contains information on a configured or to-be-configured route.
No description provided by the author
Represents the signature portion of the webhook POST body.
Stats as returned by `GetStats()`.
StoredAttachment structures contain information on an attachment associated with a stored message.
StoredMessage structures contain the (parsed) message content for an email sent to a Mailgun account.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Stats on temporary failures.
Total stats for messages.
The tracking status of a domain.
This error will be returned whenever a Mailgun API returns an error response.
No description provided by the author
No description provided by the author
No description provided by the author
Represents the JSON payload provided when a Webhook is called by mailgun.
No description provided by the author
No description provided by the author

# Interfaces

No description provided by the author
All events returned by the EventIterator conform to this interface.
Mailgun defines the supported subset of the Mailgun API.

# Type aliases

Specify the access of a mailing list member.
Used by GetStats() to specify the resolution stats are for.
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.
No description provided by the author
No description provided by the author