What are the benefits of using Swiftmailer as an alternative to the mail() function in PHP for sending emails?

Using Swiftmailer as an alternative to the mail() function in PHP for sending emails provides several benefits, such as better support for attachments, HTML emails, and SMTP authentication. Swiftmailer also offers more robust error handling and debugging capabilities, making it a more reliable and secure option for sending emails.

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

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