Hoppa till innehållet

Frameworks

Echo

The Go SDK, sendora.se/go/sendora, sends an Echo app’s mail through the API. Its webhook handler checks each delivery’s signature, and Echo serves it as a route. This guide’s samples run on Echo 5.4 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 Echo and the SDK:

go get github.com/labstack/echo/v5 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.go makes the client as the app starts, and serves the routes that the sections below write:

package main

import (
	"cmp"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	"github.com/labstack/echo/v5"
	"github.com/labstack/echo/v5/middleware"
	"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)
	}

	e := echo.New()
	e.Use(middleware.RequestLogger())
	e.Use(middleware.Recover())
	e.POST("/contact", contact(client))
	e.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())

	// Echo's e.Start sets one limit, of 30 seconds.
	server := &http.Server{
		Handler:           e,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       15 * time.Second,
		IdleTimeout:       time.Minute,
	}
	log.Fatal(server.Serve(listener))
}
  • sendora.NewClientFromEnv() reads the key from SENDORA_API_TOKEN. Without a key, it returns an error, and the app stops before it listens.
  • Make one client and share it. It is safe for use by many goroutines at once, and it keeps its connections between calls.
  • Echo’s e.Start is meant for examples and demos, as its comment says. The server it starts sets one time limit, of 30 seconds. So the app serves Echo on a server of its own, with the three limits set.
  • Run it with go run .. It listens on localhost:8080, or on the port in PORT.

Send mail

The handler in contact.go sends a contact form’s message to your support address:

package main

import (
	"net/http"
	"net/mail"

	"github.com/labstack/echo/v5"
	"sendora.se/go/sendora"
)

func contact(client *sendora.Client) echo.HandlerFunc {
	return func(c *echo.Context) error {
		visitor, err := mail.ParseAddress(
			c.FormValue("email"),
		)
		message := c.FormValue("message")
		if err != nil || message == "" {
			return echo.NewHTTPError(
				http.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.Request().Context()
		accepted, err := client.Email.Send(ctx, email)
		if err != nil {
			// Echo's request logger writes the error.
			return echo.NewHTTPError(
				http.StatusServiceUnavailable,
				"Try again later.",
			).Wrap(err)
		}

		answer := map[string]string{
			"messageId": accepted.MessageID,
		}
		return c.JSON(http.StatusAccepted, 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.ParseAddress, 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.
  • Sendora refuses a header value that holds a line break, so the visitor’s address cannot add a header of its own.
  • Send returns the accepted message, with Sendora’s MessageID, 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, Send returns a *sendora.Error, whose Code is the error code. The handler wraps it in an echo.HTTPError, and Echo’s request logger writes it on the request’s line. 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.Email.Send(ctx, email, sendora.WithIdempotencyKey("order-1042-shipped")). A retry with the same key returns the first answer and sends nothing.

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.

  1. Add the route, webhooks.go. This one logs a hard bounce, and files each received mail as Received mail explains:
package main

import (
	"context"
	"log"

	"github.com/labstack/echo/v5"
	"sendora.se/go/sendora"
)

func webhookRoute(
	client *sendora.Client,
	secret string,
) (echo.HandlerFunc, error) {
	// 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
	}

	// Without the secret, it returns an error.
	webhooks, err := sendora.NewWebhookHandler(
		secret,
		handle,
	)
	if err != nil {
		return nil, err
	}
	return echo.WrapHandler(webhooks), nil
}
  1. Create a webhook under the server’s Webhooks tab, with the address of the route, such as https://example.se/sendora/webhook. If the app receives mail, create it through the API instead, as Received mail says.
  2. Put its secret in SENDORA_WEBHOOK_SECRET, and deploy.

echo.WrapHandler turns the SDK’s http.Handler into an Echo route. That handler reads the body as Sendora sent it, and checks its signature before it parses anything. Then it calls your function with the event, as a type of its own such as *sendora.BouncedEvent, 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.
  • 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, webhookRoute returns 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.UnknownEvent, which the type switch’s default takes. So the route answers 204 to it.
  • The route takes the largest delivery that Limits gives, so an inbound event with its content fits. A proxy in front of the app may allow less, so allow the route that size there too.
  • Echo’s BodyLimit middleware refuses a body over its limit. Keep the webhook’s route out of it, or give it a limit no lower than that size.
  • 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_WEBHOOK_SECRET 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.

Received mail

The route above files each received mail. An inbound event has the message’s InboundMessageID, and tickets.go 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 InboundContent set to sendora.InboundContentReference. A webhook from the dashboard carries the whole mail in each inbound event, as Inbound explains.
  • Only a DMARC pass proves 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 Text nil.
  • 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_test_.

  1. Create a test server under Servers › New server, with Testserver ticked, and a key on its API keys tab.
  2. Put the key in SENDORA_API_TOKEN on your machine, and in CI. Keep a live server’s key in production.
  3. Send to the simulator’s addresses, such as hardbounce@simulator.sendora.se, to act out a bounce or a complaint. The message’s events show in the dashboard’s message log, as Messages and events explains.

main.go above refuses a test key where mail must arrive. With APP_ENV set to production, the app stops before it listens. Without APP_ENV, 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_test.go tests both routes:

package main

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"github.com/labstack/echo/v5"
	"sendora.se/go/sendora"
	"sendora.se/go/sendora/sendoratest"
)

func TestTheFormMailsSupport(t *testing.T) {
	stub := sendoratest.NewServer(t)
	e := echo.New()
	e.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(echo.HeaderContentType,
		echo.MIMEApplicationForm)
	recorder := httptest.NewRecorder()
	e.ServeHTTP(recorder, request)

	sent := stub.Sent()
	if recorder.Code != http.StatusAccepted ||
		len(sent) != 1 {
		t.Fatalf("answered %d", recorder.Code)
	}
	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)
	}
	e := echo.New()
	e.POST("/sendora/webhook", route)

	body := sendoratest.EventJSON(
		sendora.WebhookEventNameBounced,
	)
	request := sendoratest.WebhookRequest(
		"/sendora/webhook", body, secret)
	recorder := httptest.NewRecorder()
	e.ServeHTTP(recorder, request)

	if recorder.Code != http.StatusNoContent {
		t.Errorf("answered %d", recorder.Code)
	}
}

Run it with go test ./.... The tests need no key or secret in the environment, and they send nothing.