What are common issues with using the mail() function in PHP for sending emails?

Common issues with using the mail() function in PHP for sending emails include emails being marked as spam, emails not being delivered, and potential security vulnerabilities. To improve email deliverability and prevent emails from being marked as spam, it is recommended to set proper headers, use a reliable mail server, and authenticate the sender. Additionally, using a library like PHPMailer can help streamline the process and provide more robust features for sending emails securely.

// Example using PHPMailer library for sending emails securely

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

require 'vendor/autoload.php'; // Include PHPMailer library

$mail = new PHPMailer(true); // Create a new PHPMailer instance

try {
    $mail->isSMTP(); // Set mailer to use SMTP
    $mail->Host = 'smtp.example.com'; // Specify main and backup SMTP servers
    $mail->SMTPAuth = true; // Enable SMTP authentication
    $mail->Username = 'your@example.com'; // SMTP username
    $mail->Password = 'yourpassword'; // SMTP password
    $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587; // TCP port to connect to

    $mail->setFrom('your@example.com', 'Your Name'); // Set sender
    $mail->addAddress('recipient@example.com', 'Recipient Name'); // Add a recipient
    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = 'Subject of the email';
    $mail->Body = 'Body of the email';

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