What are the advantages of using a pre-built mailer like SwiftMailer or PhpMailer over the mail() function in PHP?

Using a pre-built mailer like SwiftMailer or PhpMailer over the mail() function in PHP offers advantages such as better support for attachments, HTML emails, SMTP authentication, and more robust error handling. These libraries provide a more object-oriented approach to sending emails, making it easier to customize and maintain your email sending functionality.

// Example code using PhpMailer to send an email with attachments

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer();

// Set up the SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set the sender and recipient
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');

// Add attachments
$mail->addAttachment('path/to/file1.pdf');
$mail->addAttachment('path/to/file2.jpg');

// Set the email subject and body
$mail->Subject = 'Test Email with Attachments';
$mail->Body = 'This is a test email with attachments.';

// Send the email
if ($mail->send()) {
    echo 'Email sent successfully';
} else {
    echo 'Error sending email: ' . $mail->ErrorInfo;
}