How to add headers in php mail functionality

When sending emails using PHP's mail() function or a PHP mail library like PHPMailer, you can add headers to the email using the From, Reply-To, Subject, and CC headers. Here's an example of how to add headers using the mail() function:

$headers = array(
    'From' => '[email protected]',
    'Reply-To' => '[email protected]',
    'Subject' => 'Test Email',
    'CC' => '[email protected]'
);

mail('[email protected]', 'Test Email', 'This is a test email', implode("\r\n", $headers));

In this example, the $headers array contains the email headers. The mail() function takes four arguments: the recipient's email address, the subject, the message body, and the headers.

Alternatively, you can use a PHP mail library like PHPMailer, which provides a more flexible and powerful way to send emails. Here's an example of how to add headers using PHPMailer:

require_once 'PHPMailer/PHPMailer.php';
require_once '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->setFrom('[email protected]', 'Your Name');
$mail->addReplyTo('[email protected]', 'Your Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email';
$mail->addCC('[email protected]');

$mail->send();

In this example, the setFrom() method sets the From header, the addReplyTo() method sets the Reply-To header, and the Subject property sets the Subject header. The addCC() method adds the CC header.

You can also add custom headers using the addCustomHeader() method:

$mail->addCustomHeader('X-Priority', '1');
$mail->addCustomHeader('X-Mailer', 'PHPMailer');

This will add the X-Priority and X-Mailer headers to the email.

Note that some email clients may not support all of the headers you add, so it's a good idea to test your email functionality thoroughly to ensure that it works as expected.