PHP Sending Email - Using the mail() Function


Sending email from a PHP script is a common requirement for web applications. PHP provides a built-in function called `mail()` that allows you to send emails. In this guide, you'll learn how to use the `mail()` function to send emails in PHP.


Step 1: Configure Your Server

Before you can send emails with PHP, make sure your server is properly configured to send email. You may need to configure an SMTP server or use your hosting provider's email services. Contact your hosting provider for specific details.


Step 2: Use the `mail()` Function

The `mail()` function in PHP is used to send email. Here's a basic example:


        <?php
$to = "recipient@example.com";
$subject = "Hello, World!";
$message = "This is a test email sent from PHP.";
$headers = "From: sender@example.com";

if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email delivery failed.";
}
?>

In the code above, replace `"recipient@example.com"` with the recipient's email address and `"sender@example.com"` with your own email address. This code will send a simple email.


Step 3: Sending HTML Emails

You can send HTML-formatted emails by setting appropriate headers. For example:


        $headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

Step 4: Sending Attachments

To send email attachments, you can use the `mail()` function in conjunction with external libraries like PHPMailer or Swift Mailer.


Conclusion

You've learned the basics of sending email using the `mail()` function in PHP. Remember to configure your server properly, handle email content securely, and consider using additional libraries for advanced email features.