#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
Creating A Simple Web Server With Golang
In this tutorial I'll be demonstrating how to create a very simple web server using Google's GoLang programming language.
Concurrency With Golang Goroutines
In this tutorial we examine how we can build concurrent highly performant go programs using goroutines.
Creating a RESTful API With Golang
this tutorial demonstrates how you can create your own simple RESTful JSON api using Go(Lang)