Write PHP program how to send mail using PHP. — To send an email using PHP on XAMPP, follow these step-by-step instructions:
Make sure XAMPP is installed on your system. You can download it from the official XAMPP website and follow the installation instructions for your operating system.
PHP uses the mail() function to send emails. To make it work on XAMPP, you’ll need to configure the php.ini file to use a mail server.
Locate the php.ini file:
• Open the XAMPP Control Panel.
• Click on “Config” next to Apache, then select “php.ini.”
• This will open the php.ini file in your default text editor.
Edit php.ini settings: Look for the following line and update it as needed:
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = smtp.gmail.com
smtp_port = 587
Uncomment and set the sendmail_from and sendmail_path directive as below
sendmail_from = <--your gmail id-->
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
Save the file after making these changes.
C:\xampp\sendmail\sendmail.ini
in File Explorer.smtp_server=smtp.gmail.com
smtp_port=587
smtp_ssl=auto
auth_username=<--your gmail id-->
auth_password=<--Follow step 5 to get password-->
hostname=localhost
Click here and follow steps to get app password
After making the changes to php.ini and sendmail.ini, restart Apache through the XAMPP Control Panel to apply the changes.
Create a PHP file (e.g., send_email.php) in the htdocs folder of XAMPP.
You can navigate to htdocs folder through path given C:\xampp\htdocs\
Add the code you shared:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$to = "example@gmail.com"; // Replace with the recipient's email address
$subject = "Test Email";
$message = "This is a test email sent from a PHP script.";
// Set the From header and other optional headers
$headers = "From: Your Name <your-email@example.com>" . "\r\n" .
"Reply-To: example@gmail.com" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Email sending failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Send Email</title>
</head>
<body>
<h1>Send Email</h1>
<form method="post">
<input type="submit" value="Send Email">
</form>
</body>
</html>
Open your browser.
Go to http://localhost/send_email.php.
Click the “Send Email” button to trigger the email