Frameworks
More ways to use this page
Fiber
The Go SDK, sendora, sends a Fiber app’s mail through the API. Its sendora checks each delivery’s signature in a Fiber route. This guide’s samples run on Fiber 3.7 with Go 1.27 or newer.
Before you start
- A server key, which you create on the server’s API keys tab in the dashboard. A test server’s key works before Sendora approves your account, and it delivers nothing.
- A verified sending domain for the From address. A test server checks the domain too.
Install
In your app’s module, install Fiber and the SDK:
go get github.com/gofiber/fiber/v3 sendora.se/go/sendora
The samples below are the files of that module’s main package.
Settings
Set the server key and the webhook’s secret in the environment that runs the app, and keep both out of git. You get the secret once you create the webhook, as Webhooks below shows.
export SENDORA_API_TOKEN=sk_…
export SENDORA_WEBHOOK_SECRET=whsec_…
main makes the client as the app starts, and serves the routes that the sections below write:
package main
import (
"cmp"
"log"
"net"
"os"
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/logger"
"github.com/gofiber/fiber/v3/middleware/recover"
"sendora.se/go/sendora"
)
func main() {
key := os.Getenv("SENDORA_API_TOKEN")
production := os.Getenv("APP_ENV") == "production"
if production && sendora.IsTestKey(key) {
log.Fatal("SENDORA_API_TOKEN is a test key;" +
" nothing would be delivered")
}
// It reads the same key, and fails without one.
client, err := sendora.NewClientFromEnv()
if err != nil {
log.Fatal(err)
}
webhooks, err := webhookRoute(
client,
os.Getenv("SENDORA_WEBHOOK_SECRET"),
)
if err != nil {
log.Fatal(err)
}
app := fiber.New(fiber.Config{
// Sendora's largest webhook delivery.
BodyLimit: 20 * 1024 * 1024,
// Fiber sets no time limit of its own.
ReadTimeout: 15 * time.Second,
IdleTimeout: time.Minute,
})
app.Use(logger.New())
app.Use(recover.New())
app.Post("/contact", contact(client))
app.Post("/sendora/webhook", webhooks)
// Sendora posts only to HTTPS, so a proxy or a
// tunnel in front serves this. If the proxy is on
// another host or container, listen on ":"+port.
port := cmp.Or(os.Getenv("PORT"), "8080")
listener, err := net.Listen("tcp", "localhost:"+port)
if err != nil {
log.Fatal(err)
}
log.Println("Listening on", listener.Addr())
log.Fatal(app.Listener(listener, fiber.ListenConfig{
DisableStartupMessage: true,
}))
}
sendorareads the key from.NewClientFromEnv() SENDORA_. Without a key, it returns an error, and the app stops before it listens.API_ TOKEN - Make one client and share it. It is safe for use by many goroutines at once, and it keeps its connections between calls.
- Fiber’s
ReadTimeoutandIdleTimeoutset no time limit unless you set them. Somainsets both..go - Run it with
go run .. It listens onlocalhost:8080, or on the port inPORT.
Send mail
The handler in contact sends a contact form’s message to your support address:
package main
import (
"log"
"net/mail"
"github.com/gofiber/fiber/v3"
"sendora.se/go/sendora"
)
func contact(client *sendora.Client) fiber.Handler {
return func(c fiber.Ctx) error {
visitor, err := mail.ParseAddress(
c.FormValue("email"),
)
message := c.FormValue("message")
if err != nil || message == "" {
return fiber.NewError(
fiber.StatusBadRequest,
"Send an address and a message.",
)
}
email := sendora.Email{
From: sendora.Address{
Email: "no-reply@example.se",
Name: "Example AB",
},
To: []sendora.Address{
{Email: "support@example.se"},
},
Headers: map[string]string{
"Reply-To": visitor.Address,
},
Subject: "A message from the contact form",
Text: message,
Tag: "contact-form",
}
ctx := c.Context()
accepted, err := client.Email.Send(ctx, email)
if err != nil {
log.Println("Sendora took no mail:", err)
return fiber.NewError(
fiber.StatusServiceUnavailable,
"Try again later.",
)
}
answer := fiber.Map{
"messageId": accepted.MessageID,
}
return c.Status(fiber.StatusAccepted).JSON(answer)
}
}
- The handler sends to your own address, and takes the visitor’s only for
Reply-To. A handler that sends to an address from its request would let anyone mail anyone. mail, from Go’s standard library, fails on a missing or malformed address. The handler then answers 400, as it does to a form without a message..ParseAddress - Sendora refuses a header value that holds a line break, so the visitor’s address cannot add a header of its own.
Sendreturns the accepted message, with Sendora’sMessageID, which the log and the webhooks use.- The tag sets the form’s mail apart in the log and in every webhook. Add metadata for ids of your own, such as an order’s.
- If Sendora refuses the mail,
Sendreturns a*sendora, whose.Error Codeis the error code. The handler logs it, and answers 503. The error’s message holds no address and nothing of the mail. - The SDK sends each mail under an idempotency key, so its own retries never send it twice. When a job may send the same mail twice, pass a key of your own, as in
client. A retry with the same key returns the first answer and sends nothing..Email .Send( ctx, email, sendora .WithIdempotencyKey( "order-1042-shipped"))
Webhooks
The webhook’s route checks each delivery’s signature, then handles its event. A delivery is one post of one event to your webhook.
- Add the route,
webhooks. This one logs a hard bounce, and files each received mail as Received mail explains:.go
package main
import (
"context"
"errors"
"log"
"github.com/gofiber/fiber/v3"
"sendora.se/go/sendora"
)
func webhookRoute(
client *sendora.Client,
secret string,
) (fiber.Handler, error) {
// VerifyWebhook would refuse every delivery.
if secret == "" {
return nil, errors.New(
"the webhook's signing secret is empty")
}
// An error gets a 500, and Sendora delivers the
// event again.
handle := func(
ctx context.Context,
event sendora.Event,
) error {
switch event := event.(type) {
case *sendora.BouncedEvent:
if event.Details.Hard {
log.Println("A message bounced for good",
event.MessageID)
}
case *sendora.InboundEvent:
return fileTicket(
ctx,
client,
event.InboundMessageID,
)
default:
// Every other event, a newer one included.
}
return nil
}
return func(c fiber.Ctx) error {
// The bytes that Sendora signed.
event, err := sendora.VerifyWebhook(
c.BodyRaw(),
c.Get("Sendora-Signature"),
secret,
)
if err != nil {
return fiber.ErrBadRequest
}
err = handle(c.Context(), event)
if err != nil {
return err
}
return c.SendStatus(fiber.StatusNoContent)
}, nil
}
- Create a webhook under the server’s Webhooks tab, with the address of the route, such as
https://example. If the app receives mail, create it through the API instead, as Received mail says..se/ sendora/ webhook - Put its secret in
SENDORA_, and deploy.WEBHOOK_ SECRET
Fiber is not built on net/, so the route checks each delivery itself. It passes c, the body as Sendora sent it, and the Sendora-Signature header to sendora. That function checks the signature before it parses anything. Then it returns the event, as a type of its own such as *sendora, so its Details are typed. Webhooks says when Sendora sends each event, and Webhook events lists their fields.
- The route answers 204 when your function returns nil. When your function returns an error, the route answers 500, and Sendora delivers the event again later, on the schedule that Webhooks gives.
- The route returns that error to Fiber, whose logger writes it on the request’s line.
- Sendora waits only as long as Limits says, so hand slow work to a queue.
- A delivery whose signature is missing, wrong or more than five minutes old gets 400, and your function never sees it.
- Without the secret,
webhookRoutereturns an error, and the app stops as it starts. - A delivery can arrive more than once. Key your handling on the event’s
ID, the delivery’s id, which stays the same on each attempt. - An event newer than your release of the SDK comes as an
*sendora, which the type switch’s.UnknownEvent defaulttakes. So the route answers 204 to it. - The route takes the largest delivery that Limits gives, so an
inboundevent with its content fits. A proxy in front of the app may allow less, so allow the route that size there too. - Fiber’s
BodyLimitrefuses a larger body before any route runs, and its default is lower than that size. Somainraises it, for every route of the app..go - If the app checks a CSRF token or a session in a middleware, register the webhook’s route outside it. Sendora sends neither.
- To roll the secret, create the new one, set
SENDORA_to it and restart the app, which reads the secret as it starts. Sendora signs each delivery with both until you delete the old one.WEBHOOK_ SECRET
Received mail
The route above files each received mail. An inbound event has the message’s InboundMessageID, and tickets fetches the mail by it:
package main
import (
"context"
"os"
"path/filepath"
"sendora.se/go/sendora"
)
func fileTicket(
ctx context.Context,
client *sendora.Client,
inboundMessageID string,
) error {
mail, err := client.Inbound.Get(ctx, inboundMessageID)
if err != nil {
return err
}
// Only a DMARC pass proves the From domain sent it.
folder := "tickets"
dmarc := mail.Authentication.DMARC
if dmarc != sendora.AuthVerdictPass {
folder = filepath.Join(folder, "unverified")
}
err = os.MkdirAll(folder, 0o750)
if err != nil {
return err
}
text := ""
if mail.Text != nil {
text = *mail.Text
}
name := filepath.Join(folder, inboundMessageID+".txt")
return os.WriteFile(name, []byte(text), 0o600)
}
- The route fetches the mail, so create its webhook through the API with
InboundContentset tosendora. A webhook from the dashboard carries the whole mail in each.InboundContentReference inboundevent, as Inbound explains. - Only a DMARC
passproves that the From domain sent the message. With any other verdict, the From address may be forged. - Sendora keeps the mail’s content for the stream’s retention, as Inbound says. After that, the route finds its
Textnil. - A test server has no inbound stream, so receive mail on a live server.
Develop against a test server
A test server checks and logs each mail as a live server does, and delivers none of it. Its keys start with sk_.
- Create a test server under Servers › New server, with Testserver ticked, and a key on its API keys tab.
- Put the key in
SENDORA_on your machine, and in CI. Keep a live server’s key in production.API_ TOKEN - Send to the simulator’s addresses, such as
hardbounce@, to act out a bounce or a complaint. The message’s events show in the dashboard’s message log, as Messages and events explains.simulator .sendora .se
main above refuses a test key where mail must arrive. With APP_ set to production, the app stops before it listens. Without APP_, the check lets any key through, so set it on every production machine. Leave it unset on your machine, in CI and on staging, which can then send with a test key.
Sendora posts webhooks only to a public HTTPS address, so a test server’s events cannot reach your machine. Test the routes with the SDK’s package sendoratest instead. Its stand-in Sendora answers the client in memory and records each send. Its signed examples of each event reach the webhook’s route as Sendora posts them. main_ tests both routes:
package main
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/gofiber/fiber/v3"
"sendora.se/go/sendora"
"sendora.se/go/sendora/sendoratest"
)
func TestTheFormMailsSupport(t *testing.T) {
stub := sendoratest.NewServer(t)
app := fiber.New()
app.Post("/contact", contact(stub.Client()))
form := url.Values{
"email": {"anna@example.com"},
"message": {"Where is my order?"},
}
request := httptest.NewRequest(http.MethodPost,
"/contact", strings.NewReader(form.Encode()))
request.Header.Set(fiber.HeaderContentType,
fiber.MIMEApplicationForm)
response, err := app.Test(request)
if err != nil {
t.Fatal(err)
}
sent := stub.Sent()
if response.StatusCode != http.StatusAccepted ||
len(sent) != 1 {
t.Fatalf("answered %d", response.StatusCode)
}
headers := sent[0].Emails[0].Headers
if headers["Reply-To"] != "anna@example.com" {
t.Errorf("Reply-To is %q", headers["Reply-To"])
}
}
func TestTheWebhookTakesASignedBounce(t *testing.T) {
const secret = "whsec_test"
stub := sendoratest.NewServer(t)
route, err := webhookRoute(stub.Client(), secret)
if err != nil {
t.Fatal(err)
}
app := fiber.New()
app.Post("/sendora/webhook", route)
body := sendoratest.EventJSON(
sendora.WebhookEventNameBounced,
)
request := sendoratest.WebhookRequest(
"/sendora/webhook", body, secret)
response, err := app.Test(request)
if err != nil {
t.Fatal(err)
}
if response.StatusCode != http.StatusNoContent {
t.Errorf("answered %d", response.StatusCode)
}
}
Run it with go test ./.... The tests need no key or secret in the environment, and they send nothing.