How to get cc in php mail
In PHP, you can use the mail()
function to send an email with a CC (carbon copy) recipient. Here's an example:
<?php
$to = '[email protected]';
$cc = '[email protected]';
$subject = 'Test email with CC';
$message = 'This is a test email with CC';
$headers = 'From: [email protected]'. "\r\n".
'CC: '. $cc. "\r\n".
'Subject: '. $subject;
if (mail($to, $subject, $message, $headers)) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email!';
}
?>
In this example, the $cc
variable contains the email address of the CC recipient. The $headers
variable is a string that contains the From, CC, and Subject headers. The mail()
function is then called with the $to
, $subject
, $message
, and $headers
variables.
Note that the CC
header should be in the format CC: <email_address>
. You can add multiple CC recipients by separating their email addresses with commas.
Alternatively, you can use the SwiftMailer
library, which provides a more flexible and powerful way to send emails with CC recipients. Here's an example:
<?php
require_once 'swiftmailer/lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('smtp.example.com', 587)
->setUsername('your_username')
->setPassword('your_password');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test email with CC')
->setFrom(array('[email protected]' => 'Sender Name'))
->setTo(array('[email protected]' => 'Recipient Name'))
->setCc(array('[email protected]' => 'CC Recipient Name'))
->setBody('This is a test email with CC');
if ($mailer->send($message)) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email!';
}
?>
In this example, the Swift_Message
object is created with the CC recipient added using the setCc()
method. The Swift_Mailer
object is then used to send the email using the send()
method.