Ad Code

Reusable PHPMailer Function (To + CC + BCC + Attachments)

 <?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

function sendMail($to, $subject, $message, $from_email, $from_name, $cc = [], $bcc = [], $attachments = []) {

    $mail = new PHPMailer(true);

    try {
        // SMTP SETTINGS
        $mail->isSMTP();
        $mail->Host       = "smtp.yourserver.com"; 
        $mail->SMTPAuth   = true;
        $mail->Username   = "your-email@domain.com";
        $mail->Password   = "your-smtp-password";
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = 587;

        // FROM & TO
        $mail->setFrom($from_email, $from_name);

        // To accepts single or array
        if (is_array($to)) {
            foreach ($to as $email) {
                $mail->addAddress($email);
            }
        } else {
            $mail->addAddress($to);
        }

        // CC array
        if (!empty($cc)) {
            foreach ($cc as $email) {
                $mail->addCC($email);
            }
        }

        // BCC array
        if (!empty($bcc)) {
            foreach ($bcc as $email) {
                $mail->addBCC($email);
            }
        }

        // Attachments
        if (!empty($attachments)) {
            foreach ($attachments as $file) {
                if (file_exists($file)) {
                    $mail->addAttachment($file);
                }
            }
        }

        // CONTENT
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $message;

        $mail->send();
        return true;

    } catch (Exception $e) {
        return "Mailer Error: " . $mail->ErrorInfo;
    }
}
?>

✅ How to Use

include("mail_function.php");

$to = ["user1@example.com", "user2@example.com"]; // To multiple
$cc = ["manager@example.com", "teamlead@example.com"];
$bcc = ["audit@example.com"];

$subject = "Test Mail";
$message = "<h3>Hello Team</h3><p>This is a test email.</p>";

$from_email = "support@yourdomain.com";
$from_name = "Your Company";

$attachments = ["uploads/report.pdf"];

$result = sendMail($to, $subject, $message, $from_email, $from_name, $cc, $bcc, $attachments);

if ($result === true) {
echo "Mail sent successfully!";
} else {
echo $result;
}



Post a Comment

0 Comments