Send Transactional Email from Go Fiber with JustEmails API
Go Fiber + JustEmails API: async goroutines, DKIM sends.
Go Fiber + JustEmails API: async goroutines, DKIM sends.
When transactional email sends run inside the request, they block the signup handler. If each send takes hundreds of milliseconds, a user waits that long just to see "check your inbox."
That's not acceptable.
Go gives you goroutines. Fiber gives you Express-like routing without the overhead. The JustEmails API takes JSON and returns JSON. Put them together and you get transactional email that fires off in the background while your handler returns immediately. The user sees success right away, and the email follows in the background. Everyone's happy.
We're the JustEmails team — JustEmails is built by Velocity Digital Labs. Go Fiber is its own world. The concurrency model changes everything about how you think about transactional email sends.
A working Go Fiber API with a POST endpoint that sends transactional email via the JustEmails API. The handler returns immediately with a 202 Accepted. A goroutine handles the actual send. Environment variables keep your secrets out of git. Your emails arrive with proper SPF/DKIM authentication because you're sending from a verified domain.
Before starting:
go version to check)API access requires a paid plan. This tutorial runs on the transactional API, and API access is not included in the 7-day trial — a trial account cannot issue the key Step 2 asks for, so there is no way to complete this walkthrough without subscribing first.
Quick context on sending limits: the base $49/year plan includes 1,000 transactional API emails per month, with extra capacity at $25/year per 10,000/month tier. The ceiling to size your worker pool against is the daily one — sends are capped per account per day at no more than 50 a day in the first week after your sending domain is verified, 200 in the second, and up to 500 from day 15, with mailbox sends and API sends counted against the same number, so a tier raises the monthly allowance rather than that daily cap. Verification emails, password resets and receipts cover most early-stage apps comfortably. If you're comparing SMTP vs API for transactional email, this tutorial is API-side.
Start fresh:
mkdir go-fiber-email && cd go-fiber-email
go mod init go-fiber-email
go get github.com/gofiber/fiber/v2
go get github.com/joho/godotenv
That's Fiber for routing and godotenv for loading .env files. You could skip godotenv and use OS environment variables directly — I prefer the .env approach for local development.
Create your entry point:
// main.go
package main
import (
"log"
"os"
"github.com/gofiber/fiber/v2"
"github.com/joho/godotenv"
)
func main() {
// Load .env file (ignore error in production where env vars are set directly)
_ = godotenv.Load()
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Email API running")
})
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
log.Fatal(app.Listen(":" + port))
}
Run it:
go run main.go
Hit http://localhost:3000 and you should see "Email API running." Nothing exciting yet.
Never hardcode API keys. They're easy to leak once they land in source control.
Create a .env file:
JUSTEMAILS_API_KEY=je_xxxxxxxxxxxxxxxxxxxx
FROM_EMAIL=noreply@yourdomain.com
PORT=3000
Replace the placeholder with your actual API key from the JustEmails dashboard (Settings → API keys — paid-plan only, as flagged in the prerequisites; a trial account cannot create this key). Keys start with je_, and there is no separate test mode: every key sends real mail. FROM_EMAIL must be a mailbox or alias on your verified domain.
Add .env to your .gitignore:
echo ".env" >> .gitignore
Here's the core logic. Standard library net/http is all you need — no external HTTP client required.
// email.go
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
type EmailPayload struct {
To string `json:"to"`
Subject string `json:"subject"`
HTML string `json:"html"`
Text string `json:"text,omitempty"`
}
type EmailRequest struct {
From string `json:"from"`
To []string `json:"to"`
Subject string `json:"subject"`
HTML string `json:"html"`
Text string `json:"text,omitempty"`
}
type EmailResponse struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
type EmailResult struct {
Success bool
MessageID string
Error string
}
func SendEmail(ctx context.Context, payload EmailPayload) EmailResult {
apiKey := os.Getenv("JUSTEMAILS_API_KEY")
fromEmail := os.Getenv("FROM_EMAIL")
if apiKey == "" {
return EmailResult{Success: false, Error: "Missing JUSTEMAILS_API_KEY"}
}
reqBody := EmailRequest{
From: fromEmail,
To: []string{payload.To},
Subject: payload.Subject,
HTML: payload.HTML,
Text: payload.Text,
}
jsonBody, err := json.Marshal(reqBody)
if err != nil {
return EmailResult{Success: false, Error: fmt.Sprintf("JSON marshal error: %v", err)}
}
req, err := http.NewRequestWithContext(ctx, "POST", "https://justemails.app/api/v1/send", bytes.NewBuffer(jsonBody))
if err != nil {
return EmailResult{Success: false, Error: fmt.Sprintf("Request creation error: %v", err)}
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return EmailResult{Success: false, Error: fmt.Sprintf("HTTP error: %v", err)}
}
defer resp.Body.Close()
var emailResp EmailResponse
if err := json.NewDecoder(resp.Body).Decode(&emailResp); err != nil {
return EmailResult{Success: false, Error: fmt.Sprintf("Response decode error: %v", err)}
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
errMsg := emailResp.Error.Message
if errMsg == "" {
errMsg = fmt.Sprintf("HTTP %d", resp.StatusCode)
}
return EmailResult{Success: false, Error: errMsg}
}
return EmailResult{Success: true, MessageID: emailResp.Data.ID}
}
This handles success and failure modes: missing env vars, JSON encoding issues, network failures, API errors. The API answers 202 once the message is queued, with the message ID in data.id; errors come back as error.code and error.message. The 30-second timeout is generous, since the call returns at queueing rather than delivery.
Why the Text field? Some email clients prefer plain text. Including both improves deliverability marginally.
Now the interesting part. We want the handler to return immediately while the email sends in the background.
// main.go
package main
import (
"context"
"log"
"os"
"regexp"
"time"
"github.com/gofiber/fiber/v2"
"github.com/joho/godotenv"
)
var emailRegex = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
type SendEmailRequest struct {
To string `json:"to"`
Subject string `json:"subject"`
HTML string `json:"html"`
Text string `json:"text,omitempty"`
}
func main() {
_ = godotenv.Load()
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Email API running")
})
app.Post("/send-email", func(c *fiber.Ctx) error {
var req SendEmailRequest
if err := c.BodyParser(&req); err != nil {
return c.Status(400).JSON(fiber.Map{
"success": false,
"error": "Invalid JSON body",
})
}
// Validation
if req.To == "" || req.Subject == "" || req.HTML == "" {
return c.Status(400).JSON(fiber.Map{
"success": false,
"error": "Missing required fields: to, subject, html",
})
}
if !emailRegex.MatchString(req.To) {
return c.Status(400).JSON(fiber.Map{
"success": false,
"error": "Invalid email format",
})
}
// Copy values before goroutine — Fiber reuses context!
payload := EmailPayload{
To: req.To,
Subject: req.Subject,
HTML: req.HTML,
Text: req.Text,
}
// Fire and forget
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
result := SendEmail(ctx, payload)
if !result.Success {
log.Printf("Email send failed to %s: %s", payload.To, result.Error)
} else {
log.Printf("Email sent to %s: %s", payload.To, result.MessageID)
}
}()
return c.Status(202).JSON(fiber.Map{
"success": true,
"message": "Email queued for delivery",
})
})
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
log.Fatal(app.Listen(":" + port))
}
A few things happening here:
We copy values before the goroutine. Fiber recycles its context objects. If you pass c or c.Context() to a goroutine, you'll get weird race conditions and panics. Copy what you need into local variables first.
We use context.Background() in the goroutine. The request context goes back to Fiber's pool when the handler returns — which is immediate. The goroutine needs its own context with its own timeout.
202 Accepted, not 200 OK. This tells the client the request was received and will be processed, not that the email has gone out. Technically correct, and it sets the right expectation.
(The framework is fast because it reuses allocations aggressively — but that means you can't hold references to request data after the handler returns.)
Restart the server and hit it with curl:
go run .
In another terminal:
curl -X POST http://localhost:3000/send-email \
-H "Content-Type: application/json" \
-d '{
"to": "your-real-email@example.com",
"subject": "Test from Go Fiber",
"html": "<h1>It works!</h1><p>Sent via JustEmails API from Go Fiber.</p>"
}'
A successful response looks like:
{
"success": true,
"message": "Email queued for delivery"
}
Check your logs — you should see either a success message with the message ID, or a failure reason. Check your inbox too. If it landed in spam, your domain's email authentication might need attention. Our DMARC enforcement guide covers the DNS setup.
The fire-and-forget goroutine approach works, but it has a problem: unbounded concurrency. 10,000 requests in a second? 10,000 goroutines. Memory exhausted. File descriptors gone. Your server is now a very expensive paperweight.
Here's a simple channel-based worker pool:
// worker.go
package main
import (
"context"
"log"
"time"
)
var emailQueue = make(chan EmailPayload, 100)
func StartEmailWorkers(count int) {
for i := 0; i < count; i++ {
go emailWorker(i)
}
log.Printf("Started %d email workers", count)
}
func emailWorker(id int) {
for payload := range emailQueue {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
result := SendEmail(ctx, payload)
cancel()
if !result.Success {
log.Printf("[Worker %d] Email failed to %s: %s", id, payload.To, result.Error)
} else {
log.Printf("[Worker %d] Email sent to %s: %s", id, payload.To, result.MessageID)
}
}
}
func QueueEmail(payload EmailPayload) bool {
select {
case emailQueue <- payload:
return true
default:
// Queue is full
return false
}
}
Update your handler to use the queue (and drop the context and time imports from main.go, which nothing there uses any more):
// In main.go, replace the goroutine section with:
if !QueueEmail(payload) {
return c.Status(503).JSON(fiber.Map{
"success": false,
"error": "Email queue is full, try again later",
})
}
return c.Status(202).JSON(fiber.Map{
"success": true,
"message": "Email queued for delivery",
})
And start the workers in main():
func main() {
_ = godotenv.Load()
// Start 5 email workers
StartEmailWorkers(5)
// ... rest of setup
}
Now you have bounded concurrency. Five workers process the queue. If the queue fills up (100 pending emails), you return 503 instead of accepting unbounded work. Adjust the numbers based on your expected volume.
For production at scale, consider Asynq or similar Redis-backed job queues. They give you persistence, retries, and monitoring. But at the volumes the daily sending ceiling allows, the in-memory channel approach is fine.
"Missing JUSTEMAILS_API_KEY" in logs
Your .env file isn't loading. Check:
.env (not env or .env.local)?go run?godotenv.Load() before reading env vars?401 Unauthorized from JustEmails
Your API key is wrong, revoked or expired. Create a new one under Settings → API keys. Make sure you're copying the full key including the je_ prefix.
403 Forbidden from JustEmails
The from address isn't one you can send from: its domain isn't verified, or the address isn't a mailbox or alias on that domain. Add the domain in the dashboard, add the DNS records, wait for verification, and create the from address as a mailbox or alias. JustEmails won't send from unverified domains — that's by design.
Email lands in spam
Ugh. This one's annoying. Check your domain's email authentication — run a test through mail-tester.com. Our custom domain setup guide walks through DNS configuration. (Email deliverability is one of those problems that feels like it should be solved by now. It isn't.)
Context canceled errors
You're probably passing Fiber's context to the goroutine instead of using context.Background(). Fiber recycles its context when the handler returns. The goroutine needs its own context.
Here's a complete verification email endpoint (it uses fmt, so add that to main.go's imports):
app.Post("/send-verification", func(c *fiber.Ctx) error {
var req struct {
Email string `json:"email"`
VerificationURL string `json:"verificationUrl"`
UserName string `json:"userName,omitempty"`
}
if err := c.BodyParser(&req); err != nil {
return c.Status(400).JSON(fiber.Map{"success": false, "error": "Invalid JSON"})
}
if req.Email == "" || req.VerificationURL == "" {
return c.Status(400).JSON(fiber.Map{"success": false, "error": "Missing email or verificationUrl"})
}
greeting := "Hi"
if req.UserName != "" {
greeting = "Hi " + req.UserName
}
html := fmt.Sprintf(`
<div style="font-family: -apple-system, sans-serif; max-width: 600px; margin: 0 auto;">
<h2>Verify your email</h2>
<p>%s,</p>
<p>Click the button below to verify your email address:</p>
<a href="%s"
style="display: inline-block; background: #0070f3; color: white;
padding: 12px 24px; text-decoration: none; border-radius: 6px;
margin: 16px 0;">
Verify Email
</a>
<p style="color: #666; font-size: 14px;">
If you didn't create an account, ignore this email.
</p>
</div>
`, greeting, req.VerificationURL)
payload := EmailPayload{
To: req.Email,
Subject: "Verify your email address",
HTML: html,
Text: fmt.Sprintf("Verify your email by visiting: %s", req.VerificationURL),
}
if !QueueEmail(payload) {
return c.Status(503).JSON(fiber.Map{"success": false, "error": "Queue full"})
}
return c.Status(202).JSON(fiber.Map{"success": true, "message": "Verification email queued"})
})
You've got a working email endpoint with async processing. Here's what to build next:
Add retry logic. Network blips happen. For critical emails like password resets, implement exponential backoff. The worker pool pattern makes this easier — failed sends can re-queue with a delay.
Track your usage. The base plan includes 1,000 API sends a month. If you're hitting that consistently, add a 10,000/month tier for $25/year — which lifts the monthly allowance, not the daily sending ceiling.
Set up webhooks. JustEmails can POST to your endpoint when emails bounce or get marked as spam. Useful for updating user records (marking emails as undeliverable). Add the endpoint under Settings → Webhooks.
Go Fiber is underrated for API work. Fast. Low memory footprint. Familiar routing if you're coming from Express. Honestly, I'm surprised more Node developers haven't made the jump. The email integration we just built is typical Fiber — standard library HTTP client, goroutines for concurrency, channels for backpressure. No magic. Just straightforward code that does what you'd expect.
HTTP handlers should return fast. Each send is a network round trip to the API, and blocking the handler means your user waits. Fire off a goroutine, return immediately with a 202 Accepted, and let the email send happen in the background. For production, use a worker pool or channel-based queue to avoid spawning unbounded goroutines under load.
Yes — Fiber reuses contexts from a pool, so passing c.Context() to a goroutine is dangerous. Copy any values you need (email address, subject, body) into local variables before spawning the goroutine. The goroutine should use context.Background() or its own timeout context for the HTTP call to JustEmails.
The base $49/year plan includes 1,000 transactional API emails per month. If your Go API sends more, add 10,000 emails/month for $25/year — stackable. A tier raises the monthly allowance only; the daily sending ceiling still applies to API sends. Most SaaS apps doing verification and password reset emails stay well under 1,000/month.
Your user won't see it since you already returned 202. Log the error, and for critical emails like password resets, consider a retry queue. Redis-backed job queues like Asynq work well with Go. For MVP apps, logging the failure and manually resending is often enough.
JustEmails is $49 a year, flat, for unlimited custom domains and unlimited mailboxes with a unified inbox across all of them — additional team members are $2 per member per month, and storage beyond the included 10 GB is $99 a year per 100 GB. Built for agencies, freelancers, and anyone managing email across more than one domain.