What are the recommended best practices for sending emails in PHP, considering issues with SMTP servers and dynamic IP addresses?

When sending emails in PHP, it's important to consider issues with SMTP servers and dynamic IP addresses. To ensure successful email delivery, it's recommended to use a reliable SMTP server with proper authentication and encryption. Additionally, to avoid being flagged as spam due to dynamic IP addresses, consider using a reputable email service provider or configuring SPF and DKIM records.

// Example PHP code snippet for sending emails using a reliable SMTP server

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    //Recipients
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body    = 'Email body';

    $mail->send();
    echo 'Email has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}