How to send mail from localhost xampp using gmail
To send mail from a localhost XAMPP setup using Gmail, you'll need to configure your PHP script to use Gmail's SMTP server. Here's a step-by-step guide to help you achieve this:
Prerequisites:
- XAMPP installed on your local machine.
- PHP version 5.3 or higher.
- A Gmail account with 2-Step Verification disabled (or set up an app password if you have 2-Step Verification enabled).
Step 1: Enable Less Secure Apps in Gmail
To allow your localhost to send emails using Gmail, you need to enable "Less Secure Apps" in your Google Account settings. Follow these steps:
- Sign in to your Gmail account.
- Click on your profile picture or initial in the top right corner, then select "My Account."
- Scroll down to the "Signing in to Google" section.
- Click on "Apps with account access."
- Look for "Less secure app access" and toggle the switch to "On."
Step 2: Configure PHP to use Gmail's SMTP server
Create a new file named php.ini
in your XAMPP's php
directory (usually C:\xampp\php
on Windows or /opt/lampp/etc/php.ini
on Linux/Mac). Add the following lines at the end of the file:
[mail function]
smtp_port = 587
smtp_host = "smtp.gmail.com"
smtp_user = "your-gmail-username"
smtp_pass = "your-gmail-password"
Replace your-gmail-username
and your-gmail-password
with your actual Gmail credentials.
Step 3: Test your PHP mail function
Create a new PHP file (e.g., test-mail.php
) and add the following code:
<?php
ini_set('SMTP', 'smtp.gmail.com');
ini_set('smtp_port', 587);
ini_set('auth_username', 'your-gmail-username');
ini_set('auth_password', 'your-gmail-password');
$to = '[email protected]';
$subject = 'Test email from localhost';
$message = 'This is a test email sent from localhost using Gmail.';
mail($to, $subject, $message);
echo 'Email sent successfully!';
?>
Replace [email protected]
with the email address you want to send the email to.
Step 4: Run the PHP script
Open a web browser and navigate to http://localhost/test-mail.php
(or the URL of your PHP file). If everything is set up correctly, you should see the message "Email sent successfully!".
Troubleshooting tips:
- Make sure you've enabled "Less Secure Apps" in your Google Account settings.
- Check your PHP error logs for any errors related to the mail function.
- Verify that your Gmail account is not set up to require 2-Step Verification (or use an app password if you have 2-Step Verification enabled).
- If you're still having issues, try using a different SMTP server or a third-party mail service.
By following these steps, you should be able to send emails from your localhost XAMPP setup using Gmail.