Flask
A small helper, registered on the app, called from a route.
Install
pip install flask emailssh python-dotenv# .env. The key comes from https://emails.sh/dashboard/api-keys.
EMAILSSH_API_KEY=esh_your_key_hereThe app
# app.py
import os
from dotenv import load_dotenv
from emailssh import Emailssh, EmailsshError
from flask import Flask, jsonify, request
load_dotenv()
app = Flask(__name__)
mail = Emailssh(api_key=os.environ["EMAILSSH_API_KEY"])
@app.post("/signup")
def signup():
address = (request.json or {}).get("email", "")
if "@" not in address:
return jsonify(error="Enter an email address."), 400
try:
sent = mail.send(
from_="Acme <hello@acme.com>",
to=[address],
subject="Welcome to Acme",
html="<p>Confirm your address to finish signing up.</p>",
text="Confirm your address to finish signing up.",
idempotency_key=f"signup-{address}",
)
except EmailsshError as err:
# err says what to do about it; the user gets something they can act on.
app.logger.error("emails.sh refused the send: %s", err)
return jsonify(error="Could not send the confirmation email."), 502
return jsonify(id=sent["id"])
if __name__ == "__main__":
app.run(port=5000)A send is a network call on the request path. Under any real traffic, hand it to Celery, RQ, or a thread and answer the user first.