How to create mail script in php

Creating a mail script in PHP involves several steps:

  1. Configure your PHP settings: Make sure that the mail() function is enabled in your PHP configuration. You can check this by creating a simple PHP file with the following code:

    <?php
    phpinfo();
    ?>

    Run this file and look for the mail() function in the output. If it's not enabled, you'll need to configure your PHP settings to allow it.

  2. Set the mail headers: Define the sender's email address, recipient's email address, and the subject of the email using the following variables:

    $from = '[email protected]';
    $to = '[email protected]';
    $subject = 'Test Email';
  3. Set the mail body: Define the email body using the following variable:

    $message = 'This is a test email sent using PHP.';
  4. Use the mail() function: Use the mail() function to send the email. The function takes four arguments:

    • to: The recipient's email address.
    • subject: The subject of the email.
    • message: The email body.
    • headers: An optional string containing additional headers.
      
      $headers = 'From: '. $from. "\r\n".
           'Reply-To: '. $from. "\r\n".
           'MIME-Version: 1.0'. "\r\n".
           'Content-Type: text/plain; charset=UTF-8';

mail($to, $subject, $message, $headers);

5. **Optional: Use a mail library or SMTP server**: If you're having trouble sending emails using the `mail()` function, you can use a mail library like PHPMailer or SwiftMailer, or set up an SMTP server to send emails.

Here's the complete code:
```php
<?php

$from = '[email protected]';
$to = '[email protected]';
$subject = 'Test Email';
$message = 'This is a test email sent using PHP.';

$headers = 'From: '. $from. "\r\n".
           'Reply-To: '. $from. "\r\n".
           'MIME-Version: 1.0'. "\r\n".
           'Content-Type: text/plain; charset=UTF-8';

mail($to, $subject, $message, $headers);

?>

Note: Make sure to replace [email protected] and [email protected] with your actual email addresses.

Troubleshooting tips: