# Gửi email giao dịch bằng Python

> Gửi email giao dịch từ Python với SDK Sendtern. Kiểm thử trong Email Playground và theo dõi quá trình gửi thật bằng ID email.

## Điều kiện trước

- Một Sendtern [khóa API](https://sendtern.com/vi/docs/authentication) được lưu như `SENDTERN_API_KEY`
- Python 3.9 trở lên

1. **Cài đặt SDK**: Chạy lệnh này trong dự án.

```
python -m pip install https://github.com/Sendtern/sendtern-sdks/releases/download/v0.3.0/sendtern-0.3.0-py3-none-any.whl
```

2. **Gửi thư điện tử**: Tạo `send.py` rồi chạy `python send.py`.

```
import os
from sendtern import Sendtern

client = Sendtern(os.environ["SENDTERN_API_KEY"])
result = client.emails.send({
  "from": "Acme <hello@mail.example.com>",
  "to": "you@example.com",
  "subject": "Welcome to Acme",
  "text": "Thanks for signing up."
})
print(result["id"])
```

3. **Kiểm tra phản ứng**: Một yêu cầu thành công sẽ trả lại `200 OK` với id email. Dùng nó để tìm email sau này.

```
{
  "id": "47be30ca-24b7-48fb-b35d-ff287b89e66d"
}
```

## Kiểm thử trước khi gửi

Lưu ví dụ thành `preview.py` rồi chạy `python preview.py`. Mở [Email Playground](https://sendtern.com/vi/dashboard/playground) để kiểm tra nội dung và tiêu đề thư trước khi thiết lập tên miền gửi.

```
import os
from sendtern import Sendtern

client = Sendtern(os.environ["SENDTERN_API_KEY"])
result = client.emails.capture({
  "from": "sandbox@sendtern.test",
  "to": "recipient@example.com",
  "subject": "Welcome email preview",
  "html": "<p>Thanks for signing up.</p>"
})
print(result["id"])
```

Khi gửi thư thật, dùng ID trong phản hồi để [kiểm tra các sự kiện gửi thư](https://sendtern.com/vi/docs/statuses). Xem [các gói email giao dịch](https://sendtern.com/vi/pricing) để biết giới hạn gửi hằng tháng.

> **tip:** Thay thế người gửi ví dụ bằng một địa chỉ trên [domain xác thực](https://sendtern.com/vi/docs/domains) của bạn.
