What are common pitfalls when sending emails using PHP mail() function on different servers?

Common pitfalls when sending emails using PHP mail() function on different servers include emails being marked as spam, emails not being delivered at all, or emails being blocked by the server's security settings. To solve these issues, it is recommended to set proper headers, use a reliable SMTP server, and ensure that the server's firewall or security settings do not block outgoing emails.

// Set proper headers to prevent emails from being marked as spam
$headers = 'From: your_email@example.com' . "\r\n" .
    'Reply-To: your_email@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

// Use a reliable SMTP server to send emails
ini_set('SMTP', 'smtp.yourserver.com');
ini_set('smtp_port', 25);

// Send email using PHP mail() function
$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email.';
$mail_sent = mail($to, $subject, $message, $headers);

if ($mail_sent) {
    echo 'Email sent successfully.';
} else {
    echo 'Failed to send email.';
}