How can PHP be used to interact with server-side email programs like postfix for advanced email forwarding tasks?

To interact with server-side email programs like postfix for advanced email forwarding tasks, PHP can be used to connect to the server via IMAP or SMTP protocols. This allows PHP scripts to access and manipulate email messages stored on the server, including forwarding them to different addresses based on specific criteria.

// Connect to the IMAP server
$hostname = '{localhost:993/imap/ssl}INBOX';
$username = 'username';
$password = 'password';

$mailbox = imap_open($hostname, $username, $password) or die('Cannot connect to mailbox: ' . imap_last_error());

// Get all messages in the INBOX
$emails = imap_search($mailbox, 'ALL');

// Loop through each email and forward if necessary
foreach ($emails as $email_number) {
    $header = imap_headerinfo($mailbox, $email_number);
    
    // Check criteria for forwarding
    if ($header->from[0]->mailbox == 'example' && $header->from[0]->host == 'domain.com') {
        // Forward email to a different address
        $forward_address = 'forward@example.com';
        imap_mail($forward_address, $header->subject, imap_body($mailbox, $email_number));
    }
}

// Close the connection
imap_close($mailbox);