What are some best practices for handling SMTP server responses in PHP scripts?

When sending emails via an SMTP server in PHP scripts, it is important to handle server responses properly to ensure the delivery status of the email. One best practice is to check for successful responses (such as a 250 code) and handle any errors or failures accordingly. This can help troubleshoot any issues with email delivery and improve the overall reliability of the email sending process.

// Example of handling SMTP server responses in PHP
$socket = fsockopen('smtp.example.com', 25, $errno, $errstr, 30);
if (!$socket) {
    echo "Error connecting to SMTP server: $errstr ($errno)";
} else {
    $response = fgets($socket);
    if (substr($response, 0, 3) != '220') {
        echo "Error: Unexpected response from SMTP server: $response";
    } else {
        // Send email data and check for response codes
        fputs($socket, "HELO example.com\r\n");
        $response = fgets($socket);
        if (substr($response, 0, 3) != '250') {
            echo "Error: HELO command failed: $response";
        }
        // Continue sending email data and checking responses
    }
    fclose($socket);
}