How can the PHPMailer library be used to send emails in PHP, and what are some common errors that may occur during setup?
To send emails in PHP using the PHPMailer library, you need to first install the library using Composer or downloading it directly from GitHub. Then, you can create a new PHP file and use the PHPMailer classes to set up the email content, recipient, sender, and other necessary information before sending the email. Common errors that may occur during setup include incorrect SMTP settings, missing required files, or issues with file permissions.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email content goes here';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>
Related questions
-
regular expressions PHP image URLs
-
PHP MySQL CSV
-
MySQL temporary tables performance optimization