# Email forwarding

Read and set the email forwarding rules on a domain that uses the registrar's forwarding service.

Read and set the email forwarding rules on a domain. Each rule forwards mail sent to a prefix at the domain to a destination address.

<Note>
  Email forwarding depends on the registrar module backing your account. The current sandbox registrar returns a `501` "Function not supported by the registrar module" for both calls. The shapes below describe the intended behavior on a registrar that supports forwarding; the observed sandbox response is shown at the end of each section.
</Note>

## Get email forwarding

Return the forwarding rules for a domain.

`GET /domains/{domain}/email`

### Parameters

<ParamField path="domain" type="text" required>
  The domain to read, for example `example.com`.
</ParamField>

### Request

<CodeGroup>
```bash cURL
API_KEY="your-api-key"
EMAIL="you@example.com"
ENDPOINT="https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php"
TS=$(date -u +"%y-%m-%d %H")
TOKEN=$(printf '%s' "$API_KEY" \
  | openssl dgst -sha256 -hmac "$EMAIL:$TS" -hex \
  | sed 's/^.*= //' | tr -d '\n' | base64 -w0)
curl -s "$ENDPOINT/domains/example.com/email" \
  -H "username: $EMAIL" \
  -H "token: $TOKEN"
```

```php PHP
<?php
$apiKey   = "your-api-key";
$email    = "you@example.com";
$endpoint = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php";

$token = base64_encode(hash_hmac("sha256", $apiKey, "{$email}:" . gmdate("y-m-d H")));

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "{$endpoint}/domains/example.com/email");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    "username: {$email}",
    "token: {$token}",
]);
echo curl_exec($curl);
curl_close($curl);
```

```python Python
from datetime import datetime, timezone

API_KEY  = "your-api-key"
EMAIL    = "you@example.com"
ENDPOINT = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php"

def token() -> str:
    ts = datetime.now(timezone.utc).strftime("%y-%m-%d %H")
    digest = hmac.new(f"{EMAIL}:{ts}".encode(), API_KEY.encode(), hashlib.sha256).hexdigest()
    return base64.b64encode(digest.encode()).decode()

resp = requests.get(f"{ENDPOINT}/domains/example.com/email",
                    headers={"username": EMAIL, "token": token()})
print(resp.status_code, resp.json())
```

```javascript Node.js

const API_KEY  = "your-api-key";
const EMAIL    = "you@example.com";
const ENDPOINT = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php";

function token() {
  const ts = new Date().toISOString().slice(2, 13).replace("T", " "); // "yy-mm-dd HH" UTC
  const digest = crypto.createHmac("sha256", `${EMAIL}:${ts}`).update(API_KEY).digest("hex");
  return Buffer.from(digest, "utf8").toString("base64");
}

const res = await fetch(`${ENDPOINT}/domains/example.com/email`, {
  headers: { username: EMAIL, token: token() },
});
console.log(res.status, await res.json());
```

```go Go
package main

	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"time"
)

const (
	apiKey   = "your-api-key"
	email    = "you@example.com"
	endpoint = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php"
)

func token() string {
	ts := time.Now().UTC().Format("06-01-02 15") // yy-mm-dd HH
	mac := hmac.New(sha256.New, []byte(email+":"+ts))
	mac.Write([]byte(apiKey))
	return base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(mac.Sum(nil))))
}

func main() {
	req, _ := http.NewRequest("GET", endpoint+"/domains/example.com/email", nil)
	req.Header.Set("username", email)
	req.Header.Set("token", token())
	resp, _ := http.DefaultClient.Do(req)
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}
```
</CodeGroup>

### Response

On a registrar that supports forwarding, this returns the current rules. On the sandbox registrar it returns:

```json
{"error":"Function not supported by the registrar module"}
```

## Save email forwarding

Replace the forwarding rules on a domain. Send matching `prefix[]` and `forwardto[]` arrays: the first prefix forwards to the first destination, and so on.

`POST /domains/{domain}/email`

### Parameters

<ParamField path="domain" type="text" required>
  The domain to update, for example `example.com`.
</ParamField>
<ParamField body="prefix" type="array">
  The local parts to forward, for example `info`. Repeat as `prefix[]` for each rule.
</ParamField>
<ParamField body="forwardto" type="array">
  The destination addresses, aligned by index with `prefix`. Repeat as `forwardto[]` for each rule.
</ParamField>

### Request

<CodeGroup>
```bash cURL
curl -s "$ENDPOINT/domains/example.com/email" \
  -H "username: $EMAIL" \
  -H "token: $TOKEN" \
  --data "prefix[]=info" \
  --data "forwardto[]=me@example.com"
```

```php PHP
<?php
// Reuse the auth setup from the get example above.
$fields = http_build_query([
    "prefix"    => ["info"],
    "forwardto" => ["me@example.com"],
]);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "{$endpoint}/domains/example.com/email");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    "username: {$email}",
    "token: {$token}",
]);
echo curl_exec($curl);
curl_close($curl);
```

```python Python
data = [
    ("prefix[]", "info"),
    ("forwardto[]", "me@example.com"),
]

resp = requests.post(f"{ENDPOINT}/domains/example.com/email",
                     headers={"username": EMAIL, "token": token()},
                     data=data)
print(resp.status_code, resp.json())
```

```javascript Node.js
const body = new URLSearchParams();
body.append("prefix[]", "info");
body.append("forwardto[]", "me@example.com");

const res = await fetch(`${ENDPOINT}/domains/example.com/email`, {
  method: "POST",
  headers: { username: EMAIL, token: token() },
  body,
});
console.log(res.status, await res.json());
```

```go Go
// Add "net/url" and "strings" to the imports.
form := url.Values{}
form.Add("prefix[]", "info")
form.Add("forwardto[]", "me@example.com")

req, _ := http.NewRequest("POST", endpoint+"/domains/example.com/email", strings.NewReader(form.Encode()))
req.Header.Set("username", email)
req.Header.Set("token", token())
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
```
</CodeGroup>

### Response

On a registrar that supports forwarding, this returns a success status once the rules are stored. On the sandbox registrar it returns:

```json
{"error":"Function not supported by the registrar module"}
```
