How can SMTP settings impact the successful delivery of emails in PHP scripts?

SMTP settings impact the successful delivery of emails in PHP scripts by specifying the outgoing mail server and authentication details required to send emails. If the SMTP settings are incorrect or not properly configured, emails may not be delivered successfully. To solve this issue, ensure that the SMTP settings in your PHP script are accurate and match the settings provided by your email service provider.

// Set SMTP settings
$smtpHost = 'smtp.example.com';
$smtpUsername = 'your_smtp_username';
$smtpPassword = 'your_smtp_password';
$smtpPort = 587;

// Send email using PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = $smtpHost;
    $mail->SMTPAuth = true;
    $mail->Username = $smtpUsername;
    $mail->Password = $smtpPassword;
    $mail->SMTPSecure = 'tls';
    $mail->Port = $smtpPort;

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

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

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