# Forwarding incoming e-mail messages to a script file

> Pipe incoming email to a script in cPanel to automate tasks such as creating help desk tickets or processing messages.

Source: https://helpcenter.ruachost.com/email/cpanel-email/forwarding-incoming-e-mail-messages-to-a-script-file/

cPanel allows you to configure e‑mail forwarders not only to other addresses but also to **pipe messages directly into a script**. This is useful for automating tasks such as help desk ticket creation, mailing list management, or custom processing.

## How It Works

- Instead of delivering mail to a mailbox, cPanel can **pipe the message** into a script.
- The script runs on the server and processes the message in real time.
- Common use cases:

  - Help desk systems (e.g., automatically creating support tickets).
  - Mailing list managers.
  - Custom automation (e.g., logging, parsing attachments).

## Steps to Forward Mail to a Script

1. **Log in to cPanel**.
2. On the **Tools page**, go to **Email → Forwarders**.
3. Under **Create an Email Account Forwarder**, click **Add Forwarder**.
4. Enter the **address to forward** (e.g., `support@example.com`).
5. Under **Destination**, select **Pipe to a Program**.
6. Enter the **relative path** to your script file.

   - Example:

     ```
     home/username/public_html/scripts/parse_mail.php
     ```
   - Do **not** include leading slashes (`/`).
7. Click **Add Forwarder**.

## Script Requirements

- The script must be executable by the server.
- It should read the incoming message from **standard input (stdin)**.
- Example in PHP:

```
#!/usr/bin/php -q
<?php
// Read email from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
    $email .= fread($fd, 1024);
}
fclose($fd);

// Process the email (example: log to file)
file_put_contents("/home/username/mail_log.txt", $email, FILE_APPEND);
?>
```

- Ensure the script has correct **permissions** (usually `755`).
- Place the script in a secure directory (outside public_html if possible).

> **Note:**
- Piping bypasses mailbox storage—messages are not saved unless your script does so.
- Test thoroughly to avoid losing important mail.
- If the script fails, messages may bounce back to the sender.
- For advanced setups, consider using frameworks like **Exim filters** or third‑party ticketing systems.
