Gin Transactional Email API (2026): Notify That a Certificate Is Ready from a Gin Handler with POST /emails
Send transactional email from a Go Gin handler with Rovela’s HTTP API: a net/http client, environment variables for the Bearer key, a “your certificate is ready to download” notice, and Idempotency-Key. Clearly Gin — not a rewrite of the Go language tour or the Go OTP guide.
Gin already has a handler; transactional email belongs in a service, not in a template
A Go Gin app can render a download page, but the work that needs a secret still has to run in a handler or a service the handler calls: net/http talking to an email API, with the Bearer key read from the process environment. Transactional email — “your certificate is ready to download,” with a time-limited URL — is that kind of work. The natural way to send it is one HTTPS POST from your own server code, not an SMTP session, and not a browser call that would expose the key.
Rovela’s Email API is built for that. There is no client library to install and no official Go or Gin SDK in the public docs. Do not look for one in this guide. The base URL is https://api.rovela.dev. You authenticate with Authorization: Bearer re_… (Authentication) and queue a message with POST /emails. The response is a message id. HTTP 200 means the message was accepted and queued, not that it has already arrived (Quick Start).
This is not a redo of the Go language tour, not a rewrite of Go OTP email, and not a second pass at send email from Go. Those articles already exist. It is also not a contacts, topics, or broadcasts product tour. It is everyday app mail from a Gin handler: a small emails service using the standard net/http client, environment variables for the key, a route that sends after a certificate becomes downloadable, an Idempotency-Key on anything a retry or a double click might repeat, and documented error handling around the {statusCode, name, message} envelope. Nearby compiled-server walkthroughs such as Ktor, Spring Boot, ASP.NET Core, and Rust cover those stacks; this article covers the Gin shape.
If you are still choosing between HTTP and SMTP, read Email API vs SMTP. Rovela’s SMTP is mailbox SMTP for mail apps (mx.rovela.dev:465, a device credential, send-as-self, 30 messages a minute from one client address). Programmatic volume from a Gin process belongs on POST /emails, which is also the distinction drawn in Email API vs SMTP relay.
What you need before the first Gin send
The first-email guide and the Quick Start are the same five steps, whether your caller is curl or net/http inside a Gin handler:
- Create an account. You start on the free plan, which sends real mail. There is no separate sandbox or test key.
- Add and verify a sending domain (a subdomain such as
mail.example.comis a common choice). You cannot send from a domain you have not verified; an unverified or foreignfromis refused with a 400 that names the domain. The dashboard asks for four DNS records — SPF, DKIM, DMARC, and return-path. See the domain setup guide and what domain email is. - Create an API key. A
sending_accesskey can send and nothing else — the right default for a production certificate notifier. Afull_accesskey can also read messages and events, and manage domains, templates, and webhooks. The full key is shown once. - Send with
POST /emails. - Confirm delivery in the dashboard, with
GET /emails/:idorGET /emails/:id/events(those reads needfull_accessor a dashboard session), or with a webhook.
from is a string in the documented form "Certificates <certs@yourdomain.com>". The address must sit on a verified sending domain. That is the same rule that makes domain email trustworthy: you prove you control the domain before you speak as it. How the display name and the address work is covered in the From name guide.
At least one of html, text, or template is required. Send both html and text where you can — many clients preview the text part, which is often where a person first sees the download URL (HTML email API).
A net/http service and environment variables
Keep the key on the server. Never put it in a Gin HTML template, a public /download page the browser can view-source, or a compiled asset you ship to a desktop helper. A leaked sending_access key can send mail as your domain.
Private values belong in the process environment (or your host’s secret store) and are read with os.Getenv only inside the service. A missing key should fail when the service is constructed, not halfway through issuing a certificate.
# environment (server only; never commit the live key)
ROVELA_API_KEY=re_your_sending_key
ROVELA_FROM=Certificates <certs@mail.example.com>
// emails.go — Gin service, standard net/http, no official SDK
package emails
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
type ApiError struct {
StatusCode int
Name string
Message string
}
func (e *ApiError) Error() string {
if e.Message != "" {
return e.Message
}
return fmt.Sprintf("Rovela: HTTP %d", e.StatusCode)
}
type Client struct {
http *http.Client
apiKey string
from string
}
func NewClient() (*Client, error) {
apiKey := os.Getenv("ROVELA_API_KEY")
from := os.Getenv("ROVELA_FROM")
if apiKey == "" || from == "" {
return nil, fmt.Errorf("missing ROVELA_API_KEY or ROVELA_FROM")
}
return &Client{
http: &http.Client{Timeout: 15 * time.Second},
apiKey: apiKey,
from: from,
}, nil
}
type SendOpts struct {
To any
Subject string
HTML string
Text string
ReplyTo any
Tags map[string]string
IdempotencyKey string
}
func (c *Client) Send(ctx context.Context, opts SendOpts) (id string, err error) {
body := map[string]any{"from": c.from, "to": opts.To, "subject": opts.Subject}
if opts.HTML != "" {
body["html"] = opts.HTML
}
if opts.Text != "" {
body["text"] = opts.Text
}
if opts.ReplyTo != nil {
body["reply_to"] = opts.ReplyTo
}
if opts.Tags != nil {
body["tags"] = opts.Tags
}
raw, err := json.Marshal(body)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.rovela.dev/emails", bytes.NewReader(raw))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Content-Type", "application/json")
if opts.IdempotencyKey != "" {
req.Header.Set("Idempotency-Key", opts.IdempotencyKey)
}
res, err := c.http.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
payload, _ := io.ReadAll(res.Body)
var parsed map[string]any
_ = json.Unmarshal(payload, &parsed)
if res.StatusCode >= 400 {
code, _ := parsed["statusCode"].(float64)
name, _ := parsed["name"].(string)
msg, _ := parsed["message"].(string)
if code == 0 {
code = float64(res.StatusCode)
}
return "", &ApiError{StatusCode: int(code), Name: name, Message: msg}
}
id, _ = parsed["id"].(string)
return id, nil
}
The JSON body and headers are the same ones the Emails API documents. Construct the client once when the Gin engine starts, and inject it into handlers — do not reread a config file on every request if you can avoid it, and do not log the key.
A Gin handler that sends after a certificate is ready
A certificate download notice is easy to double-send: the issuer retries a webhook, a user clicks “regenerate” twice, or two workers close the same issuance job. Put the send behind your own certificate record, and give every issuance a stable Idempotency-Key that includes the certificate id. An Idempotency-Key may be up to 256 characters; a retry of the same request within 24 hours returns the original response instead of sending again (idempotency).
The sketch below is a Gin route. This is still your code calling POST /emails. It is not a Rovela-Gin plugin, and it is not a generic main.go rewrite of the Go language tour.
// handlers.go
package main
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"yourapp/emails"
)
type readyRequest struct {
CertificateID string `json:"certificateId"`
Recipient string `json:"email"`
DownloadURL string `json:"downloadUrl"`
ExpiresAt string `json:"expiresAt"`
}
func CertificateReady(client *emails.Client) gin.HandlerFunc {
return func(c *gin.Context) {
var body readyRequest
if err := c.ShouldBindJSON(&body); err != nil || body.CertificateID == "" || body.Recipient == "" || body.DownloadURL == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "certificateId, email, and downloadUrl are required"})
return
}
// Persist "certificate is ready" in your own store, then send.
// This guide does not invent a Rovela certificates API.
html := fmt.Sprintf(`<p>Your certificate is ready to download.</p><p><a href="%s">%s</a></p><p>This link expires at %s.</p>`, body.DownloadURL, body.DownloadURL, body.ExpiresAt)
text := fmt.Sprintf("Your certificate is ready to download.\n%s\nThis link expires at %s.", body.DownloadURL, body.ExpiresAt)
id, err := client.Send(c.Request.Context(), emails.SendOpts{
To: body.Recipient,
Subject: "Your certificate is ready to download",
HTML: html,
Text: text,
Tags: map[string]string{
"purpose": "certificate-ready",
"certificate_id": body.CertificateID,
},
IdempotencyKey: "certificate-ready:" + body.CertificateID,
})
if err != nil {
var apiErr *emails.ApiError
if errors.As(err, &apiErr) {
// The certificate can still be downloadable; mail is queued asynchronously.
c.JSON(http.StatusOK, gin.H{"certificate": "ready", "emailError": apiErr.Message})
return
}
c.Error(err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "send failed"})
return
}
c.JSON(http.StatusOK, gin.H{"certificate": "ready", "emailId": id})
}
}
Register the handler on a route such as r.POST("/certificates/:id/ready", CertificateReady(client)) after you construct the client in main. DownloadURL and ExpiresAt are your domain fields. This article does not invent a Rovela files API — issue the certificate however your app already does, then pass the recipient address and the download URL to POST /emails.
If you later need many personalized messages in one go — a course that issues a stack of certificates after an exam window closes — use batch (POST /emails/batch, up to 100 messages, each processed independently). template and topic_id are rejected on batch rather than ignored; send those through POST /emails. See the batch example and the batch transactional email guide.
Errors you should handle in the service
Every documented error uses the same envelope, so one ApiError covers them (Quick Start, Email API error handling):
{ "statusCode": 400, "name": "Bad Request", "message": "html or text body is required" }
The message says what was wrong. Surface it in your Gin logs as-is.
400— a missing required field, a base64 attachment that does not decode, afromdomain that does not belong to your organization, atemplatethat does not exist, or more than 50 recipients on one message.401— missing or invalid credential, or asending_accesskey used to read, reschedule, or cancel a message.429— rate limit exceeded. The first-email guide notes that the rate limit is per key, and that each message in a batch counts individually. The official batch example waits onRetry-Afterwhen that header is present (and falls back to one second if it is not). This article will not invent a requests-per-second number, because the public docs do not publish one. Retries of a failed HTTP call should reuse the same idempotency key (Email API retries, rate limits).
HTTP 200 on send is not delivery. If you need to look a message up later, GET /emails/:id and GET /emails/:id/events require a full_access key or a dashboard session — do not put that key in the same client you call from every issuance. Managing sending domains is a different API and a different key scope (Domains API, Email API authentication, sending domains API). A sending_access key used on a management endpoint such as GET /domains is documented as 403; that is not the same as a failed send.
A handler should not fail the issuance just because mail queued slowly. Record that the certificate is ready, log the error, and let your webhook or a later retry (with the same idempotency key) finish the notice.
Delivery is asynchronous — do not poll from the handler
The handler should record the message id and return. Confirm delivery in the dashboard, with the Email delivery status API, or with a webhook. For production, prefer a webhook over polling GET /emails/:id from the certificate route. An issuance request should not wait on inbox arrival.
A webhook endpoint in Gin is another handler that reads the raw body (c.GetRawData() or a bound raw reader), verifies x-resend-signature, and returns 2xx quickly. Verification is byte-exact HMAC-SHA256 over "<timestamp>.<raw body>" (webhook security). A 400 you return because a payload surprised you is a permanent loss; store anything you do not yet understand rather than rejecting it. Deduplicate on the event id. Managing webhook endpoints themselves is covered in the Email Webhooks API guide and the signature verification walkthrough.
When you need a message to go out later — a reminder the day before the download link expires — use scheduled_at (scheduled email). POST /emails/:id/cancel can cancel a message that has not been sent yet; reading, rescheduling, and cancelling need a full_access key or a dashboard session. Public docs do not describe a reschedule request body, so this article will not invent one. Reusable layouts belong in the Templates API and the templates guide.
What not to do in a Gin codebase
Do not invent a Rovela-Gin plugin, a dashboard click path that is not in the docs, or a special certificate object Rovela would have to provide. This integration is plain HTTP from your service.
Do not call the Emails API from a Gin HTML template or a public download page. The key would travel with the response. Call it from a handler or the service the handler uses.
Do not treat this guide as a replacement for the Go language tour or the Go OTP article, and do not treat it as a broadcast or contacts tour. Public docs for contacts, topics, segments, and broadcasts are not used as a product walkthrough here. This helper is for the mail your Gin product sends after a certificate is ready to download.
Do not point an SMTP client at Rovela mailbox SMTP and call that your application mailer. Mailbox SMTP is for mail apps: a mailbox can send only as itself, and a single client address is limited to 30 messages a minute. That is the wrong default for app volume.
Hosted mailboxes are a different product surface. People can read and send from them in a mail app. Your Gin process should not share a device credential with someone else’s Thunderbird profile.
If you issue certificates on behalf of several schools from one organization, restrict a key to a single domain so a leak cannot send as somebody else (Email API for multi-tenant SaaS). Nearby notification patterns live in the email notification API overview if you need a broader map, then come back here for the Gin shape.
If you later compare providers, the documented pages include Rovela vs Mailgun, vs Amazon SES, vs Postmark, vs SendGrid, vs Resend, and vs Brevo.
A compact Gin checklist
- Verify the sending domain before you set
from. An unverified domain is a 400, not a silent drop. - Keep
ROVELAcredentials in the process environment and construct thenet/httpclient once when the Gin engine starts. - Prefer a
sending_accesskey in production handlers; keepfull_accessfor tooling that reads events or manages webhooks. - Send both
htmlandtextwhen you can, include the download URL in both, and set anIdempotency-Keyderived from the certificate id. - Record the message
idand return from the handler. Do not fail the issuance because mail is still queueing. Watch delivery with a webhook, not a loop in the route. - If you need a first request in curl, use the transactional email API overview, the curl sending guide, or the HTTP email API explainer — then come back to this helper for the Gin shape.