In what situations would it be advisable to use PHP libraries like Swift Mailer or PHPMailer instead of the built-in mail() function for sending emails with activation links?

When sending emails with activation links, it is advisable to use PHP libraries like Swift Mailer or PHPMailer instead of the built-in mail() function for better control over the email sending process, improved security features, and support for advanced email functionalities such as HTML emails and attachments.

// Example code using PHPMailer to send an email with activation link

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

require 'vendor/autoload.php';

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

try {
    //Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    //Recipients
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Activation Link';
    $mail->Body = 'Click the following link to activate your account: <a href="http://www.example.com/activate.php?token=123456">Activate</a>';

    $mail->send();
    echo 'Email has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}