How can PHPMailer with SMTP-Auth be implemented to ensure successful email delivery in PHP scripts?
To ensure successful email delivery in PHP scripts using PHPMailer with SMTP-Auth, you need to properly configure the PHPMailer object with the SMTP server details, including the host, port, username, password, and authentication method. This allows PHPMailer to authenticate with the SMTP server before sending the email, ensuring that the email is delivered successfully.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Include PHPMailer autoloader
require 'vendor/autoload.php';
// Instantiate PHPMailer
$mail = new PHPMailer();
// Configure SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Use TLS encryption
$mail->Port = 587;
// Set email parameters
$mail->setFrom('from@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->Body = 'Body of the email';
// Send the email
if ($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Error: ' . $mail->ErrorInfo;
}