What are the advantages of using libraries like Swiftmailer for sending emails in PHP compared to the built-in mail() function?

When sending emails in PHP, using libraries like Swiftmailer provides several advantages over the built-in mail() function. Swiftmailer offers a more robust and secure way to send emails, with support for features like HTML emails, attachments, and SMTP authentication. It also simplifies the process of sending emails by providing a more user-friendly interface and better error handling capabilities.

// Using Swiftmailer to send an email in PHP

// Include the Swift Mailer autoloader
require_once 'vendor/autoload.php';

// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.example.com', 587, 'tls'))
  ->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');

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

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