How to send mail from localhost in php using phpmailer
To send mail from localhost in PHP using PHPMailer, you'll need to follow these steps:
Step 1: Install PHPMailer
You can install PHPMailer using Composer by running the following command in your terminal:
composer require phpmailer/phpmailer
Step 2: Configure PHPMailer
Create a new PHP file (e.g., sendmail.php
) and add the following code:
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Create a new PHPMailer instance
$mail = new PHPMailer();
// Set the sender's email address
$mail->setFrom('[email protected]', 'Your Name');
// Set the recipient's email address
$mail->addAddress('[email protected]');
// Set the subject of the email
$mail->Subject = 'Test Email from localhost';
// Set the body of the email
$mail->Body = 'This is a test email sent from localhost using PHPMailer.';
// Set the SMTP server settings
$mail->isSMTP();
$mail->Host = 'localhost'; // or your SMTP server's hostname
$mail->SMTPAuth = false; // or true if your SMTP server requires authentication
$mail->Port = 25; // or your SMTP server's port number
// Send the email
if (!$mail->send()) {
echo 'Error sending email: '. $mail->ErrorInfo;
} else {
echo 'Email sent successfully!';
}
Step 3: Configure your SMTP server (if necessary)
If you're using a local SMTP server (e.g., Mailhog, Mailcatcher, or a virtual mail server), you'll need to configure it to allow connections from your PHP script. Consult your SMTP server's documentation for instructions on how to do this.
Step 4: Run the script
Save the sendmail.php
file and run it using your web server or a PHP CLI tool (e.g., php sendmail.php
).
Troubleshooting tips
- Make sure your PHP script has the necessary permissions to send emails.
- Check your SMTP server settings (e.g., hostname, port, authentication) to ensure they're correct.
- Verify that your email address is valid and not blocked by your email provider.
- If you're using a local SMTP server, ensure it's running and configured correctly.
By following these steps, you should be able to send emails from your localhost using PHPMailer.