How can PHP beginners integrate PHP code for sending emails into an existing HTML-based website?

To integrate PHP code for sending emails into an existing HTML-based website, beginners can create a PHP script that handles the email sending functionality. This script can be integrated into the existing HTML pages by using PHP include or require statements. The PHP script can be triggered by a form submission on the HTML page, allowing users to input their email content and recipient details.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $to = "recipient@example.com";
    $subject = "Subject of the email";
    $message = $_POST['message'];
    $headers = "From: sender@example.com";

    if (mail($to, $subject, $message, $headers)) {
        echo "Email sent successfully!";
    } else {
        echo "Email sending failed.";
    }
}
?>

<form method="post" action="">
    <textarea name="message" rows="4" cols="50"></textarea><br>
    <input type="submit" value="Send Email">
</form>