github.com/mailgun/mailgun-go/v3@v3.6.4/README.md (about)

     1  # Mailgun with Go
     2  
     3  [![GoDoc](https://godoc.org/github.com/mailgun/mailgun-go?status.svg)](https://godoc.org/github.com/mailgun/mailgun-go)
     4  [![Build Status](https://img.shields.io/travis/mailgun/mailgun-go/master.svg)](https://travis-ci.org/mailgun/mailgun-go)
     5  
     6  Go library for interacting with the [Mailgun](https://mailgun.com/) [API](https://documentation.mailgun.com/api_reference.html).
     7  
     8  **NOTE: Backward compatibility has been broken with the v3.0 release which includes versioned paths required by 1.11 
     9  go modules (See [Releasing Modules](https://github.com/golang/go/wiki/Modules#releasing-modules-v2-or-higher)).
    10   Pin your dependencies to the v1.1.1 or v2.0 tag if you are not ready for v3.0**
    11  
    12  ## Usage
    13  ```go
    14  package main
    15  
    16  import (
    17      "context"
    18      "fmt"
    19      "log"
    20      "time"
    21  
    22      "github.com/mailgun/mailgun-go/v3"
    23  )
    24  
    25  // Your available domain names can be found here:
    26  // (https://app.mailgun.com/app/domains)
    27  var yourDomain string = "your-domain-name" // e.g. mg.yourcompany.com
    28  
    29  // You can find the Private API Key in your Account Menu, under "Settings":
    30  // (https://app.mailgun.com/app/account/security)
    31  var privateAPIKey string = "your-private-key"
    32  
    33  
    34  func main() {
    35      // Create an instance of the Mailgun Client
    36      mg := mailgun.NewMailgun(yourDomain, privateAPIKey)
    37  
    38      sender := "sender@example.com"
    39      subject := "Fancy subject!"
    40      body := "Hello from Mailgun Go!"
    41      recipient := "recipient@example.com"
    42  
    43      // The message object allows you to add attachments and Bcc recipients
    44      message := mg.NewMessage(sender, subject, body, recipient)
    45  
    46      ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    47      defer cancel()
    48  
    49      // Send the message	with a 10 second timeout
    50      resp, id, err := mg.Send(ctx, message)
    51  
    52      if err != nil {
    53          log.Fatal(err)
    54      }
    55  
    56      fmt.Printf("ID: %s Resp: %s\n", id, resp)
    57  }
    58  ```
    59  
    60  ## Get Events
    61  ```go
    62  package main
    63  
    64  import (
    65      "context"
    66      "fmt"
    67      "time"
    68  
    69      "github.com/mailgun/mailgun-go/v3"
    70      "github.com/mailgun/mailgun-go/v3/events"
    71  )
    72  
    73  func main() {
    74      // You can find the Private API Key in your Account Menu, under "Settings":
    75      // (https://app.mailgun.com/app/account/security)
    76      mg := mailgun.NewMailgun("your-domain.com", "your-private-key")
    77  
    78  	it := mg.ListEvents(&mailgun.ListEventOptions{Limit: 100})
    79  
    80  	var page []mailgun.Event
    81  
    82  	// The entire operation should not take longer than 30 seconds
    83  	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
    84  	defer cancel()
    85  
    86  	// For each page of 100 events
    87  	for it.Next(ctx, &page) {
    88  		for _, e := range page {
    89  			// You can access some fields via the interface
    90  			fmt.Printf("Event: '%s' TimeStamp: '%s'\n", e.GetName(), e.GetTimestamp())
    91  
    92  			// and you can act upon each event by type
    93  			switch event := e.(type) {
    94  			case *events.Accepted:
    95  				fmt.Printf("Accepted: auth: %t\n", event.Flags.IsAuthenticated)
    96  			case *events.Delivered:
    97  				fmt.Printf("Delivered transport: %s\n", event.Envelope.Transport)
    98  			case *events.Failed:
    99  				fmt.Printf("Failed reason: %s\n", event.Reason)
   100  			case *events.Clicked:
   101  				fmt.Printf("Clicked GeoLocation: %s\n", event.GeoLocation.Country)
   102  			case *events.Opened:
   103  				fmt.Printf("Opened GeoLocation: %s\n", event.GeoLocation.Country)
   104  			case *events.Rejected:
   105  				fmt.Printf("Rejected reason: %s\n", event.Reject.Reason)
   106  			case *events.Stored:
   107  				fmt.Printf("Stored URL: %s\n", event.Storage.URL)
   108  			case *events.Unsubscribed:
   109  				fmt.Printf("Unsubscribed client OS: %s\n", event.ClientInfo.ClientOS)
   110  			}
   111  		}
   112  	}
   113  }
   114  ```
   115  
   116  ## Event Polling
   117  The mailgun library has built-in support for polling the events api
   118  ```go
   119  package main
   120  
   121  import (
   122      "context"
   123      "time"
   124  
   125      "github.com/mailgun/mailgun-go/v3"
   126  )
   127  
   128  func main() {
   129      // You can find the Private API Key in your Account Menu, under "Settings":
   130      // (https://app.mailgun.com/app/account/security)
   131      mg := mailgun.NewMailgun("your-domain.com", "your-private-key")
   132  
   133  	begin := time.Now().Add(time.Second * -3)
   134  
   135  	// Very short poll interval
   136  	it := mg.PollEvents(&mailgun.ListEventOptions{
   137  		// Only events with a timestamp after this date/time will be returned
   138  		Begin: &begin,
   139  		// How often we poll the api for new events
   140  		PollInterval: time.Second * 30,
   141  	})
   142  
   143  	ctx, cancel := context.WithCancel(context.Background())
   144  	defer cancel()
   145  
   146      // Poll until our email event arrives
   147      var page []mailgun.Event
   148      for it.Poll(ctx, &page) {
   149          for _, e := range page {
   150              // Do something with event
   151          }
   152      }
   153  }
   154  ```
   155  
   156  # Email Validations
   157  ```go
   158  package main
   159  
   160  import (
   161      "context"
   162      "fmt"
   163      "log"
   164      "time"
   165  
   166      "github.com/mailgun/mailgun-go/v3"
   167  )
   168  
   169  // If your plan does not include email validations but you have an account,
   170  // use your Public Validation api key. If your plan does include email validations,
   171  // use your Private API key. You can find both the Private and
   172  // Public Validation API Keys in your Account Menu, under "Settings":
   173  // (https://app.mailgun.com/app/account/security)
   174  var apiKey string = "your-api-key"
   175  
   176  func main() {
   177      // Create an instance of the Validator
   178      v := mailgun.NewEmailValidator(apiKey)
   179  
   180  	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
   181  	defer cancel()
   182  
   183      email, err := v.ValidateEmail(ctx, "recipient@example.com", false)
   184      if err != nil {
   185          panic(err)
   186      }
   187      fmt.Printf("Valid: %t\n", email.IsValid)
   188  }
   189  ```
   190  
   191  ## Webhook Handling
   192  ```go
   193  package main
   194  
   195  import (
   196      "context"
   197      "encoding/json"
   198      "fmt"
   199      "net/http"
   200      "os"
   201      "time"
   202  
   203      "github.com/mailgun/mailgun-go/v3"
   204      "github.com/mailgun/mailgun-go/v3/events"
   205  )
   206  
   207  func main() {
   208  
   209      // You can find the Private API Key in your Account Menu, under "Settings":
   210      // (https://app.mailgun.com/app/account/security)
   211      mg := mailgun.NewMailgun("your-domain.com", "private-api-key")
   212  
   213  	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
   214  
   215  		var payload mailgun.WebhookPayload
   216  		if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
   217  			fmt.Printf("decode JSON error: %s", err)
   218  			w.WriteHeader(http.StatusNotAcceptable)
   219  			return
   220  		}
   221  
   222  		verified, err := mg.VerifyWebhookSignature(payload.Signature)
   223  		if err != nil {
   224  			fmt.Printf("verify error: %s\n", err)
   225  			w.WriteHeader(http.StatusNotAcceptable)
   226  			return
   227  		}
   228  
   229  		if !verified {
   230  			w.WriteHeader(http.StatusNotAcceptable)
   231  			fmt.Printf("failed verification %+v\n", payload.Signature)
   232  			return
   233  		}
   234  
   235  		fmt.Printf("Verified Signature\n")
   236  
   237  		// Parse the event provided by the webhook payload
   238  		e, err := mailgun.ParseEvent(payload.EventData)
   239  		if err != nil {
   240  			fmt.Printf("parse event error: %s\n", err)
   241  			return
   242  		}
   243  
   244  		switch event := e.(type) {
   245  		case *events.Accepted:
   246  			fmt.Printf("Accepted: auth: %t\n", event.Flags.IsAuthenticated)
   247  		case *events.Delivered:
   248  			fmt.Printf("Delivered transport: %s\n", event.Envelope.Transport)
   249  		}
   250  	})
   251  
   252  	fmt.Println("Serve on :9090...")
   253  	if err := http.ListenAndServe(":9090", nil); err != nil {
   254  		fmt.Printf("serve error: %s\n", err)
   255  		os.Exit(1)
   256  	}
   257  }
   258  ```
   259  
   260  ## Using Templates
   261  
   262  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:
   263  
   264  ```go
   265  package main
   266  
   267  import (
   268      "context"
   269      "fmt"
   270      "log"
   271      "time"
   272  
   273      "github.com/mailgun/mailgun-go/v3"
   274  )
   275  
   276  // Your available domain names can be found here:
   277  // (https://app.mailgun.com/app/domains)
   278  var yourDomain string = "your-domain-name" // e.g. mg.yourcompany.com
   279  
   280  // You can find the Private API Key in your Account Menu, under "Settings":
   281  // (https://app.mailgun.com/app/account/security)
   282  var privateAPIKey string = "your-private-key"
   283  
   284  
   285  func main() {
   286      // Create an instance of the Mailgun Client
   287      mg := mailgun.NewMailgun(yourDomain, privateAPIKey)
   288  
   289      sender := "sender@example.com"
   290      subject := "Fancy subject!"
   291      body := ""
   292      recipient := "recipient@example.com"
   293  
   294      // The message object allows you to add attachments and Bcc recipients
   295  		message := mg.NewMessage(sender, subject, body, recipient)
   296  		message.SetTemplate("passwordReset")
   297  		message.AddTemplateVariable("passwordResetLink", "some link to your site unique to your user")
   298  
   299      ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
   300      defer cancel()
   301  
   302      // Send the message	with a 10 second timeout
   303      resp, id, err := mg.Send(ctx, message)
   304  
   305      if err != nil {
   306          log.Fatal(err)
   307      }
   308  
   309      fmt.Printf("ID: %s Resp: %s\n", id, resp)
   310  }
   311  ```
   312  
   313  The official mailgun documentation includes examples using this library. Go
   314  [here](https://documentation.mailgun.com/en/latest/api_reference.html#api-reference)
   315  and click on the "Go" button at the top of the page.
   316  
   317  ### EU Region
   318  European customers will need to change the default API Base to access your domains
   319  
   320  ```go
   321  mg := mailgun.NewMailgun("your-domain.com", "private-api-key")
   322  mg.SetAPIBase(mailgun.APIBaseEU)
   323  ```
   324  ## Installation
   325  
   326  If you are using [golang modules](https://github.com/golang/go/wiki/Modules) make sure you
   327  include the `/v3` at the end of your import paths
   328  ```bash
   329  $ go get github.com/mailgun/mailgun-go/v3
   330  ```
   331  
   332  If you are **not** using golang modules, you can drop the `/v3` at the end of the import path.
   333  As long as you are using the latest 1.10 or 1.11 golang release, import paths that end in `/v3`
   334  in your code should work fine even if you do not have golang modules enabled for your project.
   335  ```bash
   336  $ go get github.com/mailgun/mailgun-go
   337  ```
   338  
   339  **NOTE for go dep users**
   340  
   341  Using version 3 of the mailgun-go library with go dep currently results in the following error
   342  ```
   343  "github.com/mailgun/mailgun-go/v3/events", which contains malformed code: no package exists at ...
   344  ```
   345  This is a known bug in go dep. You can follow the PR to fix this bug [here](https://github.com/golang/dep/pull/1963)
   346  Until this bug is fixed, the best way to use version 3 of the mailgun-go library is to use the golang community 
   347  supported [golang modules](https://github.com/golang/go/wiki/Modules).
   348  
   349  ## Testing
   350  
   351  *WARNING* - running the tests will cost you money!
   352  
   353  To run the tests various environment variables must be set. These are:
   354  
   355  * `MG_DOMAIN` is the domain name - this is a value registered in the Mailgun admin interface.
   356  * `MG_PUBLIC_API_KEY` is the Public Validation API key - you can get this value from the Mailgun [security page](https://app.mailgun.com/app/account/security)
   357  * `MG_API_KEY` is the Private API key - you can get this value from the Mailgun [security page](https://app.mailgun.com/app/account/security)
   358  * `MG_EMAIL_TO` is the email address used in various sending tests.
   359  
   360  and finally
   361  
   362  * `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*.
   363  
   364  The code is released under a 3-clause BSD license. See the LICENSE file for more information.