Sending email from localhost is very useful to quickly test or debug your web application. Setting up the mail function will need a few steps.
Create send_email_test.php file. Put the following code. It uses the PHP mail() function. By default, it will not work in localhost. To fix it, we need to use the Gmail SMTP server.
<?php $send_to_email = "[email protected]"; $subject = "Verification Email"; $body = "Hi {$send_to_email}.<br /><br />"; $body .= "Test body of email"; $from_name = "YOURNAME"; $from_email = "[email protected]"; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: {$from_name} <{$from_email}> \n"; if (mail($send_to_email, $subject, $body, $headers)) { echo "Email sent."; } else { echo "Unable to send email."; }
Previously, we are using the PHPMailer library to send emails from localhost. It is not needed anymore. You can use a Gmail account to send an email from localhost.
Open your php.ini file. In my case, it is found in the C:\xampp\php directory. Find the following settings and set the values.
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
Open your sendmail.ini file. In my case, I found it in the C:\xampp\sendmail directory. Find the following settings and set the values. Change YOUROWNEMAIL and YOURGMAILPASSWORD to the account you want to use.
smtp_server=smtp.gmail.com
smtp_port=587
[email protected]
auth_password=YOURGMAILPASSWORD
You will need to see the Apache error logs and see the exact error message. Here’s how: