Mail php sender

Here is an example of a PHP script that sends an email using the mail() function:

<?php

// Define the recipient's email address
$to = '[email protected]';

// Define the subject of the email
$subject = 'Test Email';

// Define the message body
$message = 'This is a test email sent using PHP.';

// Define the sender's email address
$from = '[email protected]';

// Define the sender's name
$from_name = 'John Doe';

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

// Send the email
if (mail($to, $subject, $message, $headers)) {
    echo 'Email sent successfully!';
} else {
    echo 'Error sending email.';
}

?>

This script sends an email to the recipient's email address with the specified subject and message body. The mail() function takes four arguments:

  1. The recipient's email address
  2. The subject of the email
  3. The message body
  4. The email headers

The email headers are used to specify the sender's email address, reply-to address, and other metadata about the email.

Note that the mail() function is a built-in PHP function, but it may not work as expected on all servers or in all environments. Some servers may require additional configuration or settings to send emails successfully.

Alternatively, you can use a PHP email library such as PHPMailer or SwiftMailer to send emails. These libraries provide more advanced features and better compatibility with different email servers and environments.

Here is an example of how you can use PHPMailer to send an email:

<?php

require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();

$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');

$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using PHPMailer.';

if (!$mail->send()) {
    echo 'Error sending email.';
} else {
    echo 'Email sent successfully!';
}

?>

This script uses the PHPMailer library to send an email to the recipient's email address. The PHPMailer class provides a more flexible and customizable way to send emails compared to the built-in mail() function.