What potential issues may arise when using the mail() function in PHP for sending emails?

One potential issue that may arise when using the mail() function in PHP is that emails sent using this function may be marked as spam by email providers due to lack of proper headers or authentication. To solve this issue, you can use the PHPMailer library which provides more features for sending emails securely and reliably.

// Include the PHPMailer library
require 'path/to/PHPMailer/PHPMailerAutoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer;

// Set up the necessary parameters for sending emails
$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;

// Set the sender and recipient of the email
$mail->setFrom('sender@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');

// Set the subject and body of the email
$mail->Subject = 'Subject of the email';
$mail->Body = 'Body of the email';

// Send the email
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}