INTEGRATIONS · Published 2026-10-06 · Updated 2026-10-06 · SecureSMTP
Python
Send with the standard library — nothing to install.
There is no SecureSMTP package to install. Python’s standard library can call the API with urllib.request, or send over SMTP with smtplib.
Setup
Every request needs your site’s API key. Get it when you add the site under Sites (/app/forms/sites) in the dashboard — see Sites and API keys. Keep it in an environment variable on the server:
export SECURESSMTP_API_KEY="qcs_live_..."A send function
Save this as securessmtp.py. It sends one email and raises SecureSMTPError if the API does not answer "ok": true.
# securessmtp.py (Python 3.8 or later, standard library only)
import json
import os
import urllib.error
import urllib.request
API_URL = "https://securessmtp.com/api/v1/mail/send"
class SecureSMTPError(Exception):
def __init__(self, reason, status, result):
super().__init__(f"SecureSMTP: {reason} (HTTP {status})")
self.reason = reason
self.status = status
self.result = result
def send_email(message: dict) -> dict:
"""Send one email. Returns the API response or raises SecureSMTPError."""
req = urllib.request.Request(
API_URL,
method="POST",
data=json.dumps(message).encode("utf-8"),
headers={
"x-securessmtp-api-key": os.environ["SECURESSMTP_API_KEY"],
"Content-Type": "application/json",
},
)
try:
with urllib.request.urlopen(req, timeout=30) as res:
status = res.status
body = res.read()
except urllib.error.HTTPError as err: # 400, 401, 403 ...
status = err.code
body = err.read()
try:
result = json.loads(body)
except ValueError:
result = {}
if not result.get("ok"):
reason = result.get("reason") or result.get("error") or "request_failed"
raise SecureSMTPError(reason, status, result)
return resultPass the message as a dict (from is a Python keyword, so it cannot be a keyword argument):
from securessmtp import send_email
result = send_email({
"to": "[email protected]",
"subject": "Your order has shipped",
"html": "<p>Your order is on its way.</p>",
"text": "Your order is on its way.",
"from": {"name": "Acme Store"},
"reply_to": "[email protected]",
})
print(result["message_id"])from is an object; only name is used. Every field is listed in the API reference.
Attachments
Send the file content as base64. Up to 20 files and 15 MB in total per email.
import base64
from pathlib import Path
from securessmtp import send_email
pdf = Path("invoice-1042.pdf").read_bytes()
send_email({
"to": "[email protected]",
"subject": "Invoice 1042",
"text": "Your invoice is attached.",
"attachments": [{
"filename": "invoice-1042.pdf",
"content": base64.b64encode(pdf).decode("ascii"),
"content_type": "application/pdf",
}],
})Handle errors
from securessmtp import SecureSMTPError, send_email
try:
send_email({"to": "[email protected]", "subject": "Hello", "text": "Hi there."})
except SecureSMTPError as err:
if err.reason == "rate_limited":
... # more than 120 sends in 60 seconds: wait a minute, then retry
elif err.reason == "over_quota":
... # monthly email count used up
elif err.reason == "send_failed":
print("Not sent:", err.result.get("error"))
else:
# 400/401/403: fix the request or the key; retrying will not help
print(err, err.result.get("details"))
except OSError as err:
# Network error or timeout. The email may or may not have been sent.
print("Request failed:", err)| Response | Meaning | What to do |
|---|---|---|
200 ok: true | Accepted for sending. | Nothing. Keep message_id if you want to find the email later. |
200 rate_limited | More than 120 sends from this site in 60 seconds. | Wait a minute, then try again. |
200 over_quota | The account’s monthly email count is used up (relay mode only). | Wait for the new month, upgrade, or send from a verified domain. |
200 send_failed | The email was not sent. The error field says why. | Read error. Do not retry in a loop. |
400 invalid_payload, no_body, … | The request is wrong. details lists the fields for invalid_payload. | Fix the request. Retrying the same request fails the same way. |
400 content_flagged, ai_flagged | The content was judged to be spam. | Change the content. See Deliverability. |
401 missing_api_key, invalid_api_key | No key was sent, or the key is wrong or was rotated. | Check the environment variable on the server. |
403 site_disabled | The site is disabled. | See Blocks. |
- Check
okin the body, not only the HTTP status. Rate limit, monthly limit and send failures come back with HTTP 200. - There is no idempotency key. If a request times out, the email may already have been sent, and sending it again can deliver it twice.
- Every reason is listed in the error catalogue.
Or send over SMTP with smtplib
| Setting | Value |
|---|---|
| Host | smtp.securessmtp.com |
| Port | 587 with STARTTLS, or 465 with SSL/TLS |
| Username | securessmtp |
| Password | Your site’s API key (qcs_live_...) |
import os
import smtplib
import ssl
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "Acme Store <[email protected]>"
msg["To"] = "[email protected]"
msg["Subject"] = "Your order has shipped"
msg.set_content("Your order is on its way.")
msg.add_alternative("<p>Your order is on its way.</p>", subtype="html")
context = ssl.create_default_context()
with smtplib.SMTP("smtp.securessmtp.com", 587, timeout=30) as smtp:
smtp.starttls(context=context)
smtp.login("securessmtp", os.environ["SECURESSMTP_API_KEY"])
smtp.send_message(msg)
# Port 465 instead:
# with smtplib.SMTP_SSL("smtp.securessmtp.com", 465, context=context, timeout=30) as smtp:
# smtp.login("securessmtp", os.environ["SECURESSMTP_API_KEY"])
# smtp.send_message(msg)[email protected] with your From name, and the From address you set becomes the Reply-To. Verify your domain and the email goes out from your own address. See Domains and DNS.A refused message raises an exception with the SMTP reply code:
try:
with smtplib.SMTP("smtp.securessmtp.com", 587, timeout=30) as smtp:
smtp.starttls(context=context)
smtp.login("securessmtp", os.environ["SECURESSMTP_API_KEY"])
smtp.send_message(msg)
except smtplib.SMTPAuthenticationError:
print("Login failed: check the API key") # 535
except smtplib.SMTPResponseException as err:
print("Rejected:", err.smtp_code, err.smtp_error.decode(errors="replace"))
except smtplib.SMTPException as err:
print("SMTP error:", err)| SMTP reply | Meaning |
|---|---|
250 | Accepted. |
535 | Login failed: the password is not a valid API key. |
450 4.7.0 | Rate limit: more than 120 sends from this site in 60 seconds. Retry later. |
550 5.7.0 | Monthly email limit reached. |
550 5.7.1 | Rejected as spam, the site is disabled, or every recipient has unsubscribed. |
550 5.1.1 | Every recipient is on the suppression list. |
552 5.3.4 | Attachments are over 15 MB in total. |
4xx 4.3.0 | Temporary failure. Retry later. |
Next
- Framework examples: Django, Flask.
- Every field and response: POST /mail/send.
- SMTP details: SMTP.