Search code examples
phpxamppsmtplocalhost

PHP mail function not sending email (php.ini and sendmail.ini are both configured)


In order to work with the php mail function i configured both php.ini and sendmail.ini, by commenting all the code in the [mail function] in php.ini and pasting the following code:

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = ******@gmail.com
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

and did the same in the sendmail.ini file:

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
auth_username=******@gmail.com
auth_password=*******
force_sender=*******@gmail.com

After that, the following error stopped raising :

Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

but the mail function still don't work and displays the "Error" string as i specified in the else statement is the following code :

<?php
$sub = "TEST";
$msg = "Sent";
$rec = "*******@gmail.com";
 if(mail($rec,$sub,$msg)){
    echo "email sent";
 }else{
    echo "Error";
 }
?> 

Solution

  • To use the mail function, you need to generate an App password and assign it to auth_password in the sendmail.ini file. Here's the process:

    1-Go to your Google Account.
    2-Click on "Security".
    3-Enable "2-step verification", then click the "App Password" section.
    4-From the "Select app" dropdown, choose "Mail", and from the "Select
    device" dropdown, select "Other (Custom name)".
    5-Give the app a descriptive name, such as "Mail Client".
    6-Click "Generate".
    7-Copy the generated App Password.
    8-Paste the password as the value for auth_password in the sendmail.ini file.