#Sending Email Using Go And Mailgun

Elliot Forbes Elliot Forbes · Apr 15, 2017 · 1 min read

In this tutorial I’m going to be demonstrating how you can send email with Go and the Mailgun API. Mailgun’s API is straightforward and sending email is easy once you’ve set everything up properly.

Requirements

Implementation

First, install the mailgun-go package:

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

Here’s a basic example of sending an email using Mailgun:

package main

import (
    "context"
    "log"
    "time"

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

func SendSimpleMessage(domain, apiKey string) error {
    mg := mailgun.NewMailgun(domain, apiKey)
    m := mg.NewMessage(
        "sender@example.com",
        "Hello",
        "Testing some Mailgun!",
        "recipient@example.com",
    )
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    _, id, err := mg.Send(ctx, m)
    if err != nil {
        return err
    }

    log.Printf("Message sent with ID: %s\n", id)
    return nil
}

func main() {
    domain := "your-domain.com"
    apiKey := "your-api-key"

    if err := SendSimpleMessage(domain, apiKey); err != nil {
        log.Fatal(err)
    }
}

Replace your-domain.com and your-api-key with your actual Mailgun domain and API key.