What are some alternative methods to sending emails in PHP besides using the mail() function?

Using the mail() function in PHP to send emails can sometimes be unreliable due to server configurations or limitations. An alternative method is to use a third-party email service provider like SendGrid, Mailgun, or SMTP servers. These services provide more reliable email delivery and offer additional features like tracking, analytics, and better deliverability rates.

// Example using SendGrid API to send emails
$email = new \SendGrid\Mail\Mail();
$email->setFrom("from@example.com", "Example User");
$email->setSubject("Sending with SendGrid is Fun");
$email->addTo("to@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 'Caught exception: '. $e->getMessage() ."\n";
}