In what situations would it be advisable to use an SMTP class instead of the mail() function in PHP for sending emails?

Using an SMTP class instead of the mail() function in PHP is advisable when you need more control over the email sending process, such as setting custom headers, handling attachments, or sending emails through a secure connection. SMTP classes provide a more robust and flexible way to send emails compared to the basic functionality offered by the mail() function.

// Example of using an SMTP class to send an email
require 'path/to/PHPMailer/PHPMailerAutoload.php';

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

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

// Set email content
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->Body = 'This is the body of the email';

// Send the email
if (!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}