What is the purpose of using PHP to send emails via SMTP?

Using PHP to send emails via SMTP allows for more control and customization over the email sending process. It enables sending emails using an external SMTP server, which can be more reliable and secure than using the built-in `mail()` function. By setting up SMTP authentication, you can ensure that your emails are delivered successfully and avoid being marked as spam.

// Using PHPMailer library to send emails via SMTP
require 'vendor/autoload.php';

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

// Configure SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$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 'Email sent successfully';
} else {
    echo 'Error sending email: ' . $mail->ErrorInfo;
}