# Django

> Send your first email from a Django view by calling the MailBlastr API with requests.

Send your first email from a Django app by calling the MailBlastr REST API directly. The `mailblastr` SDK is for Node.js — Python users POST JSON to `https://api.mailblastr.com/emails` with the [`requests`](https://pypi.org/project/requests/) library from a view.

## Prerequisites

- A MailBlastr [API key](https://www.mailblastr.com/docs/api-keys/overview).
- A [verified domain](https://www.mailblastr.com/docs/domains/managing) to send from.

## 1. Install an HTTP client

**Pip**

```bash
pip install requests
```

## 2. Set your API key

Read the key from the environment so it never lives in source.

**.env**

```ini
MAILBLASTR_API_KEY=mb_xxxxxxxxx
```

## 3. Send email from a view

POST the email body to the MailBlastr API from a Django view. The easiest way to send is with the `html` field.

**views.py**

```py
import os
import requests
from django.http import JsonResponse


def send_email(request):
    res = requests.post(
        "https://api.mailblastr.com/emails",
        headers={"Authorization": f"Bearer {os.environ['MAILBLASTR_API_KEY']}"},
        json={
            "from": "Acme <onboarding@yourdomain.com>",
            "to": ["delivered@example.com"],
            "subject": "Hello from Django",
            "html": "<strong>it works!</strong>",
        },
    )
    res.raise_for_status()
    return JsonResponse({"id": res.json()["id"]})
```

For richer HTML, render a Django template to a string and pass it as the `html` field.

**views.py**

```py
from django.template.loader import render_to_string

html = render_to_string("emails/welcome.html", {
    "user_name": "Django Developer",
    "dashboard_url": "https://example.com/dashboard",
})
# ...then pass html=... in the JSON body above.
```

> **Note:** A successful call returns the created email's `id`. See every supported field in the [Send an email](https://www.mailblastr.com/docs/api/emails-send) reference.
