What potential issues can arise from using the mail() function in PHP for sending emails?
One potential issue that can arise from using the mail() function in PHP for sending emails is that it may be marked as spam by email providers due to lack of proper headers or authentication. To solve this issue, you can use a library like PHPMailer which provides better control over email headers and supports authentication methods such as SMTP.
// Example code using PHPMailer to send email with proper headers and authentication
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$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}";
}