What is the purpose of using popen to execute sendmail in PHP?

When using sendmail in PHP, the popen function can be used to execute sendmail commands from within the script. This can be useful for sending emails programmatically without relying on external libraries or services. By using popen, the script can interact with sendmail through standard input and output streams.

$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email sent using sendmail in PHP';
$headers = 'From: sender@example.com';

$sendmail = popen('/usr/sbin/sendmail -t', 'w');
fwrite($sendmail, "To: $to\n");
fwrite($sendmail, "Subject: $subject\n");
fwrite($sendmail, $headers."\n");
fwrite($sendmail, "\n");
fwrite($sendmail, $message);
pclose($sendmail);