Guide · REST API · Python

Send email with Python

To send email with Python, POST a JSON body to tinyRelay's /email/campaign endpoint using requests or the standard library's http.client, with your API key in the X-RELAY-ACCESS-TOKEN header.

Endpoint
POST /email/campaign
Auth header
X-RELAY-ACCESS-TOKEN
Success
202 · requestId
Clients
requests · http.client

Before you start

Accounts are set up with you during onboarding. For the DKIM record and the rest of your sending setup, see transactional email deliverability.

No package to install. tinyRelay works with any language that can make HTTP requests. Everything below uses a standard HTTP client.

Send email from Python, step by step

The example sends a sign-in code. Codes are short-lived secrets, so the request also turns tracking off.

1. Store your API key

Keep the key out of your code. Set it as an environment variable on the server that calls tinyRelay.

export TINYRELAY_API_KEY="your-api-key"
$env:TINYRELAY_API_KEY = "your-api-key"

2. Build the request body

Build a dict. attributes fill [FIRST_NAME] and [CODE] in the body; metadata holds your user ID and comes back on every webhook.

email.pyCopy
email = {
    "subject": "Your Acme sign-in code",
    "body": "<p>Hi [FIRST_NAME], your sign-in code is <strong>[CODE]</strong>.</p>",
    "sender": {"from": {"name": "Acme", "email": "no-reply@acme.com"}},
    "recipients": {
        "to": [
            {
                "name": "Ann Lee",
                "email": "ann@example.com",
                "attributes": {"FIRST_NAME": "Ann", "CODE": "482913"},
            }
        ]
    },
    "metadata": {"user_id": "u_1042", "flow": "sign_in_code"},
    # Codes should not be tracked: no link rewriting, no open pixel
    "disableTrackingLinks": True,
}

3. POST it to /email/campaign

Both tabs define the same send_email function. It raises on anything other than 202.

# tinyrelay.py  (pip install requests)
import os

import requests

API_URL = "https://api.tinyemail.com/v1/relay/email/campaign"


def send_email(email: dict) -> str:
    resp = requests.post(
        API_URL,
        json=email,
        headers={"X-RELAY-ACCESS-TOKEN": os.environ["TINYRELAY_API_KEY"]},
        timeout=10,
    )
    if resp.status_code != 202:
        raise RuntimeError(f"tinyRelay {resp.status_code}: {resp.text}")
    return resp.json()["requestId"]
# tinyrelay.py  (standard library only)
import http.client
import json
import os


def send_email(email: dict) -> str:
    conn = http.client.HTTPSConnection("api.tinyemail.com", timeout=10)
    try:
        conn.request(
            "POST",
            "/v1/relay/email/campaign",
            body=json.dumps(email),
            headers={
                "Content-Type": "application/json",
                "X-RELAY-ACCESS-TOKEN": os.environ["TINYRELAY_API_KEY"],
            },
        )
        resp = conn.getresponse()
        data = resp.read().decode("utf-8")
    finally:
        conn.close()
    if resp.status != 202:
        raise RuntimeError(f"tinyRelay {resp.status}: {data}")
    return json.loads(data)["requestId"]

Base URL from current site samples; confirm in the docs.

4. Check for a 202

send_email(email) returns the requestId. Log it with the user ID so support can trace the code email if a user says it never arrived.

The 202 response

A request that passes validation returns 202. That means tinyRelay accepted the send; what happens to each email afterwards arrives as webhook events.

202 Accepted · response bodyCopy
{
  "requestId": "833c5151-5a98-4bad-a30f-7cc816352b7a",
  "message": "SUCCESS"
}
  • requestId identifies this send. Store it next to your own record.
  • If you did not set campaignId, the requestId is used as the campaign ID, and every webhook event for the send carries it.
  • A 202 is not delivery. Watch for DELIVERED or BOUNCED events.

Send codes to many users in one Python request

Build recipients.to with a list comprehension. Each user gets their own code in attributes and their own user_id in metadata.

batch.pyCopy
request_id = send_email({
    "subject": "Your Acme sign-in code",
    "body": "<p>Hi [FIRST_NAME], your code is <strong>[CODE]</strong>.</p>",
    "sender": {"from": {"name": "Acme", "email": "no-reply@acme.com"}},
    "metadata": {"tenant_id": "acme", "flow": "sign_in_code"},
    "disableTrackingLinks": True,
    "recipients": {
        "to": [
            {
                "email": user.email,
                "attributes": {"FIRST_NAME": user.first_name, "CODE": code},
                "metadata": {"user_id": user.id},
            }
            for user, code in pending_codes
        ]
    },
})

The rules, from the Send Email docs:

10keys
Merged metadata map

Request-level and recipient-level maps merge. The cap is on the merged map.

Over412 · nothing sent
500recipients
With their own metadata

At most 500 recipients in one request may carry their own metadata.

Over412 · nothing sent
64chars
Key length

Each metadata key can be up to 64 characters.

Applies toevery key
256chars
Value length

Values up to 256 characters: flat strings, numbers or booleans.

Valuesflat only

attributes are merge tags rendered into the body, such as [FIRST_NAME], and never echoed on webhooks. metadata is never rendered into the email and is always echoed on webhooks.

"attributes": { "FIRST_NAME": "Ann" }     // in the email: "Hi Ann"
"metadata":   { "user_id": "u_1042" }    // on every webhook event

Request-level and recipient-level maps merge, and the recipient's keys win.

// request    { "tenant_id": "acme", "plan": "pro" }
// recipient  { "plan": "team" }
// merged     { "tenant_id": "acme", "plan": "team" }

Values must be flat strings, numbers or booleans.

{ "order_id": "SO-1", "total": 42, "gift": true }   // flat: fine
{ "order": { "id": "SO-1" } }                       // nested object: not flat

Metadata is scoped to campaignId. Reusing a campaignId across batches replaces the earlier metadata, so use a unique one per batch or leave it out.

"campaignId": "password_reset_batch_0142"   // unique per batch
// or leave it out: the requestId is used as the campaign ID

Should a code email be tracked?

For sign-in codes and other one-time secrets, most teams switch tracking off. Flip the switches to see what tracking does to a link in the email.

Tracking for this request
Open + click tracking
Link wrapping (X-Link-Wrapping: true)

Illustrative. [tracking-domain] stands for the tracking domain in your account.

"disableTrackingLinks": True turns off both link rewriting and the open pixel for the whole request. There is no setting for only one of the two, and it cannot be set per recipient.

Handle delivery webhooks

tinyRelay posts an event to your webhook endpoint for each thing that happens to an email. There are seven event types:

POST → your webhook endpoint · 7 event typessigned via Svix
  1. SENDSent to the receiving server
  2. DELIVEREDEmail delivered
  3. BOUNCEDHARD_BOUNCED or SOFT_BOUNCED · adds bounceCategory
  4. OPENOpened by the recipient
  5. CLICKA tracked link was clicked · adds url
  6. UNSUBSCRIBEUnsubscribe link clicked
  7. SPAMMarked as spam

SEND: the email was sent. Apps usually mark the message as sent against their record.

Each event carries eventType, receiver, requestId, campaignId and your merged metadata. BOUNCED events add bounceCategory, and CLICK events add the url that was clicked.

Verify, then deduplicate. Webhooks are signed with svix-id, svix-timestamp and svix-signature headers and delivered at least once, so verify each request and deduplicate on svix-id.

Read email webhooks and delivery events, then verify webhook signatures. Bounce categories are explained in the email bounce codes reference; field-level detail is in the webhook docs.

Troubleshooting

The Send Email endpoint documents four error statuses. Match the status you get to the row below.

StatusMeaningWhat to check
400MeaningBad RequestWhat to checkThe body failed validation. The response carries a message field; read it, fix the field it names and resend.
401MeaningAPI key missing or invalidWhat to checkCheck the header is named X-RELAY-ACCESS-TOKEN and holds the key issued at onboarding. If the key is right, confirm the server you are calling from has an IP on your allowlist.
405MeaningMethod Not AllowedWhat to checkSend a POST to /email/campaign. Other methods are refused.
412MeaningMetadata limits brokenWhat to checkThe merged metadata map has more than 10 keys, or more than 500 recipients carry their own metadata. Nothing is sent; trim the metadata and resend.

Full error schemas are in the Send Email API reference.

FAQ

Do I need a tinyRelay Python package?

No. There is no package to install. Use requests or the standard library's http.client to make one HTTPS POST.

Either works. requests is shorter and serializes JSON for you but is a separate install; http.client ships with Python and needs no dependencies.

Set disableTrackingLinks to True in the request body. It turns off link rewriting and the open pixel together, for the whole request.

Attributes are merge tags rendered into the email body and never echoed on webhooks. Metadata is never rendered into the email and is always echoed on webhooks.

Next steps

Get started

Send transactional email with a service that reports back.

SMTP relay or REST API, standalone or alongside tinyEmail. Tell us what you send and our team sets you up.