How To Send Mail From Localhost XAMPP Using PHP
How To Send Mail From Localhost XAMPP Using PHP.
To send mail from localhost XAMPP using Gmail, configure XAMPP after installing it.
Steps to Send Mail From Localhost XAMPP Using Gmail:
Open XAMPP Installation Directory.
- Go to
C:\xampp\phpand open thephp.inifile. - Find
[mail function]by pressingctrl + f - Search and pass the following values:
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = YourGmailId@gmail.com
sendmail_path = "C:\xampp\sendmail\sendmail.exe\"
Sign in with App Passwords to generate an app password for your account.
- Go to Google Account and sign in with your Gmail account, Make sure you are signed in with the same account you want to generate the app password for and Turn on 2-Step Verification.
- Under Select app, choose the app you want to generate the app password for. For example, Mail, Chrome, or Calendar.
- Select the mail and device you want to generate the app password for.
- Click Generate. You’ll see a 16-character app password. Copy it to your clipboard or write it down somewhere safe.
- Click Done.
Now, go to C:\xampp\sendmail and open the sendmail.ini file.
Find [sendmail] by pressing ctrl + f
Search and pass the following values
smtp_server=smtp.gmail.com
smtp_port=587 or 25 //use any of them
error_logfile=error.log
debug_logfile=debug.log
auth_username=yourgmail@gmail.com
auth_password= Paste the app password here
force_sender=YourGmailId@gmail.com(optional)
Now create a php file and paste the following code in it.
<?php
$to_email = "receipient@gmail.com";
$subject = "Simple Email Test via PHP";
$body = "Hi, This is test email send by PHP Script";
$headers = "From: sender email";
if (mail($to_email, $subject, $body, $headers)) {
echo "Email successfully sent to $to_email...";
} else {
echo "Email sending failed...";
}
Now run the php file in your browser.
If you are using XAMPP, then run the php file in your browser by typing localhost/sendmail.php in the address bar.
Possible Errors and Solutions
-
If you are getting the error
SMTP Error: Could not authenticate.then you have to generate an app password for your Gmail account. Go to https://myaccount.google.com/apppasswords and generate an app password for your Gmail account and paste it in thesendmail.inifile. -
If you are getting the error
SMTP Error: Could not connect to SMTP host.then you have to change the port number in thesendmail.inifile. Change the port number from587to25or vice versa.
Conclusion
In this article, we have learned how to send mail from localhost XAMPP using Gmail. We have also learned how to generate an app password for your Gmail account.
