<a id="module-postdelivery"></a>

<a id="post-delivery"></a>

# Post-delivery

The post-delivery script is executed after a delivery attempt or when a message is deleted or bounced from the queue. If the message was deleted from the queue (either manually or by retention) the `$context` variable will not be defined.

<a id="variables"></a>

## Variables

These are the pre-defined variables available.

| Variable                                                  | Type   | Read-only   | Description                                                         |
|-----------------------------------------------------------|--------|-------------|---------------------------------------------------------------------|
| [$arguments](#v-z1) | array  | yes         | Context/hook arguments                                              |
| [$message](#v-m1)   | array  | yes         | The queued message (with modifications from pre-delivery)           |
| $context                                                  | any    | yes         | This variable is only defined if the pre-delivery has been executed |

<a id="v-z1"></a>

<a id="arguments"></a>

### Arguments

| Array item                                             | Type    | Example                             | Description                                                                                                 |
|--------------------------------------------------------|---------|-------------------------------------|-------------------------------------------------------------------------------------------------------------|
| retry                                                  | number  | `3`                                 | The current retry                                                                                           |
| expires                                                | number  | `3600`                              | The amount of seconds that are left until the message will expire                                           |
| expired                                                | boolean | `false`                             | If the maximum age or retry count of the message has been exceeded                                          |
| action                                                 | string  | `"DELETE"`                          | The default action of this execution (`"DELETE"`, `"BOUNCE"`, `"QUEUE"`). Missing on successful deliveries. |
| grouping                                               | string  | `"&exampledomains"`                 | The matched grouping                                                                                        |
| [policy](#p2)  | array   | `["tags" => ["backoff"], "polic...` | The pickup policy information (if an attempt was made)                                                      |
| [attempt](#r1) | array   | `["result" => [ "code" => 200, ...` | The delivery attempt result (if an attempt was made)                                                        |
| [dsn](#d1)     | array   | `["action"=> "delayed", ...]`       | The DSN action and a DSN message id (if generated).                                                         |
| [queue](#i9)   | array   | `["plugin" => ["return"...]`        | The queue plugin data (not always available)                                                                |

<a id="p2"></a>

<a id="policy"></a>

#### Policy

| Array item                                              | Type   | Example                             | Description             |
|---------------------------------------------------------|--------|-------------------------------------|-------------------------|
| tags                                                    | array  | `["backoff", ...]`                  | The policy tags applied |
| [policies](#policies1) | array  | `[["fields" => ...], ["fields" ...` | The polices applied     |

<a id="policies1"></a>

<a id="policies"></a>

##### Policies

| Array item    | Type    | Example                      | Description                                                                                                                                                       |
|---------------|---------|------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| fields        | array   | `["remoteip", "recipient...` | List of matched fields; `transportid`, `localip`, `remoteip`, `remotemx`, `recipientdomain`, `tenantid`, `jobid` and `grouping`                                   |
| grouping      | array   | `["remotemx" => "#google"]`  | List of policy groupings, index on `transportid`, `localip`, `remoteip`, `remotemx`, `recipientdomain`, `tenantid`, `jobid` and `grouping` (not always available) |
| dynamic       | array   | `[0=>["id"=>"...", "tag"..]` | List of all dynamic policies applied (not always available)                                                                                                       |
| tags          | array   | `["backoff", ...]`           | The policy tags (not always available)                                                                                                                            |
| concurrency   | number  | `100`                        | The policy concurrency (not always available)                                                                                                                     |
| rate          | array   | `[5, 100]`                   | The policy rate (not always available)                                                                                                                            |
| ratealgorithm | string  | `"fixedwindow"`              | The rate algorithm, can be either `fixedwindow` or `tokenbucket` (not always available)                                                                           |
| stop          | boolean | `false`                      | If the policy evaluation was stopped due to the stop flag                                                                                                         |
| properties    | array   | `["myproperty1" => "foo"]`   | The policy properties (not always available)                                                                                                                      |

<a id="r1"></a>

<a id="attempt"></a>

#### Attempt

| Array item                                                | Type   | Example                                   | Description                                                |
|-----------------------------------------------------------|--------|-------------------------------------------|------------------------------------------------------------|
| [result](#ar1)     | array  | `["code" => 250, "enhanced" => [1, ...]`  | A SMTP protocol response (if available)                    |
| [error](#ae1)      | array  | `["temporary" => true, "message" => ...]` | A generic eror message (if no SMTP result)                 |
| [connection](#ac1) | array  | `["localip" => "1.2.3.4", "remoteip"...]` | Connection information                                     |
| duration                                                  | number | `1.012`                                   | The delivery attempt duration                              |
| [plugin](#ac1p)     | array  | `["return" => "plugin data"]`             | Custom delivery plugin return value (not always available) |

<a id="ar1"></a>

<a id="result"></a>

##### Result

| Array item                                           | Type   | Example                      | Description                                                       |
|------------------------------------------------------|--------|------------------------------|-------------------------------------------------------------------|
| code                                                 | number | `250`                        | A SMTP status code                                                |
| enhanced                                             | array  | `[2, 0, 0]`                  | A SMTP enhanced status code                                       |
| reason                                               | array  | `["Ok: queued as 18c19..."]` | A SMTP response text                                              |
| [state](#as1) | string | `"MAIL"`                     | An enum to indicate which issued SMTP command triggerd the result |

<a id="ae1"></a>

<a id="error"></a>

##### Error

| Array item                                           | Type    | Example             | Description                                                                                                                           |
|------------------------------------------------------|---------|---------------------|---------------------------------------------------------------------------------------------------------------------------------------|
| temporary                                            | boolean | `true`              | If the error may be transient                                                                                                         |
| message                                              | string  | `"A generic error"` | An error message                                                                                                                      |
| type                                                 | string  | `"dns"`             | One of `config`, `dns`, `network`, `dane`, `protocol`, `tls` or `plugin`                                                              |
| dns                                                  | string  | `"nullmx"`          | One of `other`, `nxdomain`, `nullmx`, `ipfamily`, `nodata` or `excluded` (only available if type is `dns`)                            |
| [state](#as1) | string  | `"MAIL"`            | An enum to indicate which issued SMTP command triggerd the result (only available if type is `network` (if connected) and `protocol`) |

<a id="ac1"></a>

<a id="connection"></a>

##### Connection

| Array item                                         | Type   | Example                      | Description                                                   |
|----------------------------------------------------|--------|------------------------------|---------------------------------------------------------------|
| id                                                 | string | `"c7a7890f-a080-11ed-9f..."` | The connection id                                             |
| transactions                                       | number | `1`                          | The number of transactions on this connection                 |
| localip                                            | string | `"1.2.3.4"`                  | The source IP used                                            |
| helo                                               | string | `"send.example.com"`         | The HELO hostname sent                                        |
| localipid                                          | string | `"bulkip1"`                  | The source IP ID (name) used (not always available)           |
| remoteip                                           | string | `"4.3.2.1"`                  | The remote IP connected to                                    |
| remotemx                                           | string | `"mail.example.com"`         | The remote MX used                                            |
| remotegreet                                        | array  | `["mail.example.com ESMTP"]` | The remote greet message (only available for `220` responses) |
| [tls](#atls1) | array  | `["started" => true, ...]`   | TLS information (if TLS was started)                          |

<a id="atls1"></a>

<a id="tls"></a>

###### TLS

| Array item                                              | Type    | Example                     | Description                          |
|---------------------------------------------------------|---------|-----------------------------|--------------------------------------|
| started                                                 | boolean | `true`                      | If STARTTLS was successfully started |
| protocol                                                | string  | `"TLSv1.3"`                 | The protocol (if available)          |
| cipher                                                  | string  | `"ECDHE-RSA-AES256-SHA384"` | The cipher (if available)            |
| keysize                                                 | number  | `256`                       | The keysize (if available)           |
| [peercert](#p1) | array   |                             | The peer certificate (if available)  |
| tlsrpt                                                  | string  | `"starttls-not-supported"`  | The tlsrpt error (if available)      |
| [tlsa](#tlsa1)     | array   |                             | The tlsa record (if available)       |

<a id="p1"></a>

<a id="peercert"></a>

####### Peercert

| Array item   | Type         | Example   | Description                                                                                          |
|--------------|--------------|-----------|------------------------------------------------------------------------------------------------------|
| x509         | X509Resource |           | An X509Resource to be used with the [`X509`](functions.html.md#X509) class |
| chain        | array        |           | An array of X509Resource (the chain)                                                                 |
| error        | number       | `18`      | The peer certificate validation error (see OpenSSLs SSL_get_verify_result(3))                        |

<a id="tlsa1"></a>

<a id="tlsa"></a>

####### TLSA

| Array item                                             | Type   | Example                 | Description                               |
|--------------------------------------------------------|--------|-------------------------|-------------------------------------------|
| error                                                  | array  | `["temporary" => true]` | The TLSA name resolution error (if error) |
| [records](#tlsa2) | array  | `[0=>["usage"=>3`       | The TLSA records (if successful)          |

<a id="tlsa2"></a>

<a id="records"></a>

######## Records

| Array item   | Type   | Example                      | Description              |
|--------------|--------|------------------------------|--------------------------|
| usage        | number | `3`                          | The usage                |
| selector     | number | `1`                          | The selector             |
| mtype        | number | `1`                          | The mtype                |
| data         | string | `fffffffffffffffffffffff...` | The data (in hex format) |

<a id="ac1p"></a>

<a id="plugin"></a>

##### Plugin

| Array item   | Type   | Example                 | Description                                 |
|--------------|--------|-------------------------|---------------------------------------------|
| return       | any    | `"plugin return value"` | Any type passed from custom delivery plugin |

<a id="d1"></a>

<a id="dsn"></a>

#### DSN

| Array item                                        | Type   | Example                      | Description                                                              |
|---------------------------------------------------|--------|------------------------------|--------------------------------------------------------------------------|
| action                                            | string | `"delayed"`                  | DSN type to be generated (`delayed`, `failed`, `relayed` or `delivered`) |
| [id](#id2) | array  | `["transaction" => "18..."`  | ID of the DSN message to be generated                                    |
| status                                            | array  | `[5, 0, 0]`                  | The DSN status (if available)                                            |
| diagnostictype                                    | string | `"smtp"`                     | The DSN diagnostic type (eg. `smtp` or `x-error`)                        |
| diagnosticcode                                    | string | `"500 message not accepted"` | The DSN diagnostic code                                                  |

<a id="i9"></a>

<a id="queue"></a>

#### Queue

| Array item                                            | Type   | Example                       | Description                                             |
|-------------------------------------------------------|--------|-------------------------------|---------------------------------------------------------|
| [plugin](#ai1p) | array  | `["return" => "plugin data"]` | Custom queue plugin return value (not always available) |

<a id="ai1p"></a>

<a id="id1"></a>

##### Plugin

| Array item   | Type   | Example                 | Description                                 |
|--------------|--------|-------------------------|---------------------------------------------|
| return       | any    | `"plugin return value"` | Any type passed from custom delivery plugin |

<a id="v-m1"></a>

<a id="message"></a>

### Message

| Array item                                                      | Type   | Example                      | Description                             |
|-----------------------------------------------------------------|--------|------------------------------|-----------------------------------------|
| [id](#id2)               | array  | `["transaction" => "18..."`  | ID of the message                       |
| ts                                                              | number | `1575558785.1234`            | Unix time of transaction                |
| serverid                                                        | string | `"inbound"`                  | ID of the server                        |
| sender                                                          | string | `"test@example.org"`         | Sender address (envelope), lowercase    |
| [senderaddress](#z1)    | array  | `["localpart" => "test"...]` | Sender address (envelope)               |
| recipient                                                       | string | `"test@example.org"`         | Recipient address (envelope), lowercase |
| [recipientaddress](#z1) | array  | `["localpart" => "test"...]` | Recipient address (envelope)            |
| transportid                                                     | string | `"inbound"`                  | ID of the transport profile to be used  |
| tenantid                                                        | string | `"customidentifier1"`        | Tenant ID of the message                |
| jobid                                                           | string | `"jobidentifier1"`           | Job ID of the message                   |
| priority                                                        | number | `1`                          | The queue priority                      |
| size                                                            | number | `412311`                     | Message size in bytes                   |
| [file](#f2)             | array  | `["original" => ...,]`       | The message file                        |
| [dsn](#dsn2)              | array  | `["envid" => ...,]`          | The message DSN options                 |
| context                                                         | array  | `["data" => ...,]`           | The message context data                |

<a id="id2"></a>

<a id="id"></a>

#### Id

| Array item   | Type   | Example                     | Description             |
|--------------|--------|-----------------------------|-------------------------|
| transaction  | string | `"18c190a3-93f-47d7-bd..."` | ID of the transaction   |
| queue        | number | `1`                         | Queue ID of the message |

<a id="z1"></a>

<a id="address"></a>

#### Address

| Array item   | Type   | Example         | Description            |
|--------------|--------|-----------------|------------------------|
| localpart    | string | `"test"`        | Local part of address  |
| domain       | string | `"example.org"` | Domain part of address |

<a id="f2"></a>

<a id="file"></a>

#### File

| Array item   | Type         | Example   | Description                                                                                          |
|--------------|--------------|-----------|------------------------------------------------------------------------------------------------------|
| original     | FileResource |           | An FileResource to be used with the [`File`](functions.html.md#File) class |
| modified     | FileResource |           | An FileResource to be used with the [`File`](functions.html.md#File) class |

<a id="dsn2"></a>

<a id="id3"></a>

#### DSN

| Array item   | Type   | Example                   | Description                                                       |
|--------------|--------|---------------------------|-------------------------------------------------------------------|
| envid        | string | `"abcdef@example.com"`    | The DSN ENVID                                                     |
| ret          | string | `"HDRS"`                  | The DSN RET (*HDRS* or *FULL*)                                    |
| notify       | array  | `"SUCCESS,FAILURE"`       | The DSN NOTIFY options (*NEVER*, *SUCCESS*, *FAILURE* or *DELAY*) |
| orcpt        | string | `"recipient@example.org"` | The DSN ORCPT recipient address                                   |

<a id="functions"></a>

## Functions

<a id="Queue"></a>

<a id="postdelivery.Queue"></a>

### Queue([options])

Queue the message to be retried later. This is the default action for non-permanent (temporary) errors while the retry count isn’t exceeded.
Permanent errors include 5xx SMTP responses, permanent DNS failures, etc.

* **Parameters:**
  **options** (*array*) – options array
* **Returns:**
  doesn’t return, script is terminated

The following options are available in the options array.

> * **hold** (boolean) Put the message in the hold (inactive) queue. The default is `false`.
> * **priority** (number) Change the queue priority (0 - normal, 1 - high). The default is the current *priority*.
> * **delay** (number) The delay in seconds. The default is according to the current transports retry delay.
> * **reason** (string) Optional message to be logged with the message.
> * **increment_retry** (boolean) If the retry count should be increased. The default is `true`.
> * **reset_retry** (boolean) If the retry count should be reset to zero. The default is `false`.
> * **transportid** (string) Change the transport ID. The default is the current *transportid*.
> * **quotas** (array) An array of quotas to be associated with the message, for use with [`queue_quota()`](functions.html.md#queue_quota).
> * **tenantid** (string) Set tenantid of the message.
> * **jobid** (string) Set jobid of the message.
> * **dsn** (array) The DSN settings. See [`Bounce()`](#postdelivery.Bounce) for options.
> * **dsn_delayed** (boolean) Override the current transports delay notification setting.

> **Warning**
> 
> If the message was delivered (`!isset($arguments["action"])`) this function will raise a runtime error.

> **Note**
> 
> It’s possible to forcefully queue the message exceeding its max retry.

<a id="Bounce"></a>

<a id="postdelivery.Bounce"></a>

### Bounce([options])

Delete the message from the queue, and generating a DSN (bounce) to the sender.

* **Parameters:**
  **options** (*array*) – options array
* **Returns:**
  doesn’t return, script is terminated

The following options are available in the options array.

> * **dsn** (array) The DSN settings.

The following options are available in the `dsn` array.

> * **transportid** (string) Set the transport ID. The default is either choosen by the transport or automatically assigned.
> * **recipient** (string or array) Set the recipient of the DSN, either as a string or an associative array with a `localpart` and `domain`.
> * **additional_recipients** (array of recipients) A list of additional recipients (BCC).
> * **metadata** (array) Add additional metadata (KVP) to the DSN.
> * **context** (array) Add context data (KVP) to the DSN message.
> * **from** (string or array) Set the From-header address of the DSN, either as a string or an associative array with a `localpart` and `domain`.
> * **from_name** (string) Set the From-header display name of the DSN.
> * **dkim** (array) Set the DKIM options of the DSN (`selector`, `domain`, `key` including the options available in [`MIME.signDKIM()`](functions.html.md#MIME.signDKIM)).
> * **tenantid** (string) Set tenantid of the message.
> * **jobid** (string) Set jobid of the message.
> * **priority** (number) The queue priority (0 - normal, 1 - high). The default is `0`.
> * **force_notify_success** (string) Always send a SUCCESS notification (`relayed` or `delivered`).
> * **subject** (string) A custom subject.
> * **subject_prepend** (string) A custom string to append to the subject line (in addition to the original subject).
> * **headers** (array) Array of additional headers to append to the DSN.
> * **readable_mimepart** (string) A full MIME part to be included as the human readable part of the DSN.
> * **ret** (string) Include either `FULL` (message), `HDRS` (headers only) or *false* (do not include the original message) in bounces. The default is `HDRS`.
> * **modified_original** (boolean) Included original message headers as modified by end-of-DATA script. The default is `false` (as received).
> * **fields** (array) Override the original `reportingmta` (string), `receivedfrommta` (string), `remotemta` (string), `status` (array of three numbers), `diagnosticcode` (string), `diagnostictype` (string) and `finalrecipient` (address) fields.
> * **additional_fields** (array) Array of additional fields to append to the DSN.
> * **additional_recipient_fields** (array) Array of additional fields to append to the per recipient fields in the DSN.
> * **exclude_headers** (array) Array of headers that should be removed from the original message.

```hsl
if ($arguments["action"] == "BOUNCE")
{
   Bounce(["dsn" => [
       "from_name" => "The Postmaster" // change postmaster address
   ]]);
}
```

> **Warning**
> 
> If the message was delivered (`!isset($arguments["action"])`) this function will raise a runtime error.

> **Note**
> 
> If the message has a null return path (empty sender) or the transport has DSN disabled, it will cause a [`Delete()`](#postdelivery.Delete) instead.

<a id="Delete"></a>

<a id="postdelivery.Delete"></a>

### Delete()

Delete the message from the queue, without generating a DSN (bounce) to the sender.

* **Returns:**
  doesn’t return, script is terminated

> **Warning**
> 
> If the message was delivered (`!isset($arguments["action"])`) this function will raise a runtime error.

<a id="Default"></a>

<a id="postdelivery.Default"></a>

### Default([options])

Run the default action pending the current `$arguments["action"]`. This is the default action if not calling [`Queue()`](#postdelivery.Queue), [`Bounce()`](#postdelivery.Bounce) or [`Delete()`](#postdelivery.Delete). If the message was delivered no action will be taken and the script will terminate.

* **Returns:**
  doesn’t return, script is terminated

The following options are available in the options array.

> * **dsn** (array) The DSN settings. See [`Bounce()`](#postdelivery.Bounce) for options.

<a id="SetMetaData"></a>

<a id="postdelivery.SetMetaData"></a>

### SetMetaData(metadata)

This function updates the queued message’s metadata in the hqf file. It is consequentially remembered for the next retry.
The metadata must be an array with both string keys and values.

* **Parameters:**
  **metadata** (*array*) – metadata to set
* **Return type:**
  none

> **Note**
> 
> To work-around the data type limitation of the metadata; data can be encoded using [`json_encode()`](functions.html.md#json_encode).

<a id="GetMetaData"></a>

<a id="postdelivery.GetMetaData"></a>

### GetMetaData()

Get the metadata set by [`SetMetaData()`](#postdelivery.SetMetaData). If no data was set, an empty array is returned.

* **Returns:**
  the data set by [`SetMetaData()`](#postdelivery.SetMetaData)
* **Return type:**
  array

<a id="on-script-error"></a>

## On script error

On script error the default action is taken.

<a id="on-implicit-termination"></a>

## On implicit termination

If not explicitly terminated then the default action is taken.

<a id="references"></a>

## References

<a id="as1"></a>

<a id="smtp-states"></a>

### SMTP states

|                 |                                                |
|-----------------|------------------------------------------------|
| BANNER          | The initial SMTP greeting                      |
| HELO            |                                                |
| EHLO            |                                                |
| LHLO            |                                                |
| STARTTLS        |                                                |
| AUTH-CRAM-MD5   | In reply to sending AUTH CRAM-MD5 command      |
| AUTH-PLAIN      | In reply to sending AUTH PLAIN command         |
| AUTH-LOGIN      | In reply to sending AUTH LOGIN command         |
| AUTH-LOGIN-USER | In reply to sending AUTH LOGIN username        |
| AUTH            | In reply to last command of AUTH login attempt |
| XCLIENT         | In reply to sending a XCLIENT command          |
| MAIL            |                                                |
| RCPT            |                                                |
| DATA            | In reply to sending the DATA command           |
| BDAT            | In reply to sending the BDAT command           |
| EOD             | In reply sending the End-of-DATA               |
| RSET            |                                                |
| NOOP            |                                                |
| QUIT            |                                                |
