How can one configure a mail server in PHP to avoid authentication issues when sending emails?

To avoid authentication issues when sending emails with a mail server in PHP, you can use SMTP authentication to provide credentials for the mail server. This ensures that the server can verify the sender's identity and allow the email to be sent successfully.

// Set the SMTP server settings
$smtpServer = 'mail.example.com';
$smtpUsername = 'username@example.com';
$smtpPassword = 'password';
$smtpPort = 587;

// Set the sender and recipient
$from = 'sender@example.com';
$to = 'recipient@example.com';

// Set the email subject and message
$subject = 'Test Email';
$message = 'This is a test email sent via SMTP authentication.';

// Configure PHPMailer to use SMTP
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = $smtpServer;
    $mail->SMTPAuth = true;
    $mail->Username = $smtpUsername;
    $mail->Password = $smtpPassword;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = $smtpPort;

    $mail->setFrom($from);
    $mail->addAddress($to);

    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $message;

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