#Sending Email Using Go And Mailgun
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
- A Mailgun account with verified domains
- Mailgun’s Go package: github.com/mailgun/mailgun-go
- Your Mailgun API key
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.
Adding Cross-Links and Further Reading
Continue Learning
The Best Books For Learning Golang
The definitive list of the best books you can buy whether you are a beginner, intermediate or advanced golang developer
Structured Logging in Go with log/slog - The Complete Guide
Learn structured logging in Go with the standard library log/slog package - handlers, levels, context, custom handlers, and why it replaces logrus, zap and zerolog.
An Introduction to Go Closures - Tutorial
Learn how closures work in Go with simple, practical examples. Understand lexical scoping and how closures capture and maintain their own state.
Makefiles for Go Developers
Learn how to use Makefiles in Go projects to automate builds, cross-compilation, and common dev tasks with a single `make` command.