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

One potential issue with using the mail() function in PHP for sending emails is that it may not be properly configured on the server, leading to emails not being delivered or being marked as spam. To solve this issue, it is recommended to use a third-party email service provider like SendGrid or Mailgun, which offer more reliable email delivery and better deliverability rates.

// Example of sending an email using SendGrid API
$email = new \SendGrid\Mail\Mail();
$email->setFrom("test@example.com", "Example User");
$email->setSubject("Sending with SendGrid is Fun");
$email->addTo("test@example.com", "Example User");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
    "text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);

$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
    $response = $sendgrid->send($email);
    echo "Email sent successfully";
} catch (Exception $e) {
    echo "Email not sent. Error: " . $e->getMessage();
}