Php mail example code

Here is an example of PHP code 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 code defines the recipient's email address, subject, message body, sender's email address, and sender's name. It then sets the email headers using the From, Reply-To, MIME-Version, and Content-Type headers. Finally, it sends the email using the mail() function and checks if the email was sent successfully.

Note that the mail() function is a built-in PHP function that sends an email using the mail transfer agent (MTA) on the server. The function takes four arguments: the recipient's email address, the subject of the email, the message body, and the email headers.

Also, you can use PHPMailer library which is more powerful and flexible than the built-in mail() function.

<?php

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

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

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

$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!';
}

?>

You can install PHPMailer using composer by running the following command:

composer require phpmailer/phpmailer

You can also use other libraries such as SwiftMailer, Zend_Mail, etc.