Is it recommended to use the mail() function in PHP for sending emails, or are there better alternatives like SwiftMailer?

It is generally not recommended to use the mail() function in PHP for sending emails, as it lacks important features like proper error handling, authentication, and support for attachments. Instead, using a library like SwiftMailer is a better alternative as it provides a more robust and secure way to send emails with various functionalities.

// Example code using SwiftMailer to send an email

require_once 'vendor/autoload.php';

// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
  ->setUsername('your_username')
  ->setPassword('your_password');

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message('Wonderful Subject'))
  ->setFrom(['john.doe@example.com' => 'John Doe'])
  ->setTo(['receiver@example.org', 'other@domain.org' => 'A name'])
  ->setBody('Here is the message body')
  ->addPart('<q>Here is the message body</q>', 'text/html');

// Send the message
$result = $mailer->send($message);

if($result) {
  echo 'Email sent successfully.';
} else {
  echo 'Failed to send email.';
}