How can the SMTP server of a hosting provider be utilized for sending emails through PHP, specifically when using the mail() function?

To utilize the SMTP server of a hosting provider for sending emails through PHP using the mail() function, you need to configure the SMTP settings in your PHP script. This involves setting the 'sendmail_path' directive in the php.ini file to point to the SMTP server, along with providing the necessary authentication credentials if required by the hosting provider.

// Set SMTP server settings
ini_set("SMTP", "mail.example.com");
ini_set("smtp_port", "25");

// Set additional headers
$headers = "From: sender@example.com";

// Send email using mail() function
$mail_success = mail("recipient@example.com", "Subject", "Message body", $headers);

if($mail_success){
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}