How to send a mail in php on cpanel
To send an email using PHP on a cPanel hosting, you can use the mail()
function or a PHP mail library like PHPMailer. Here's a step-by-step guide:
Method 1: Using the mail()
function
- Create a PHP file (e.g.,
send_email.php
) in your cPanel hosting's public_html directory. - Add the following code to the file:
<?php $to = '[email protected]'; // Replace with the recipient's email address $subject = 'Test Email'; $message = 'This is a test email sent using PHP'; $headers = 'From: [email protected]'. "\r\n". 'Reply-To: [email protected]'. "\r\n". 'MIME-Version: 1.0'. "\r\n". 'Content-Type: text/plain; charset=UTF-8';
if (mail($to, $subject, $message, $headers)) { echo 'Email sent successfully!'; } else { echo 'Error sending email!'; } ?>
Replace `[email protected]` with your actual email address.
3. Save the file and upload it to your cPanel hosting's public_html directory.
4. Access the file by visiting `http://yourdomain.com/send_email.php` in your browser. If everything is set up correctly, you should see the "Email sent successfully!" message.
**Method 2: Using PHPMailer**
1. Download and extract the PHPMailer library to your cPanel hosting's public_html directory.
2. Create a PHP file (e.g., `send_email.php`) in the same directory as the PHPMailer library.
3. Add the following code to the file:
```php
<?php
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'your_smtp_host'; // Replace with your SMTP host
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username'; // Replace with your SMTP username
$mail->Password = 'your_smtp_password'; // Replace with your SMTP password
$mail->Port = 587; // Replace with your SMTP port
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]'); // Replace with the recipient's email address
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using PHPMailer';
if ($mail->send()) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email!';
}
?>
Replace your_smtp_host
, your_smtp_username
, your_smtp_password
, and [email protected]
with your actual SMTP host, username, password, and email address.
- Save the file and upload it to your cPanel hosting's public_html directory.
- Access the file by visiting
http://yourdomain.com/send_email.php
in your browser. If everything is set up correctly, you should see the "Email sent successfully!" message.
Important notes:
- Make sure to replace the placeholders (e.g.,
[email protected]
) with your actual email address and other relevant information. - If you're using a cPanel hosting, you may need to configure your email settings in the cPanel control panel to allow PHP to send emails.
- Be aware that some cPanel hosting providers may have specific requirements or restrictions for sending emails using PHP.