PHP Mailgun API: Sending emails exclusively to BCC recipients?

I’m stuck trying to send emails using the Mailgun PHP API. My goal is to send messages only to BCC recipients, but I’m running into issues. Here’s what I’ve tried:

function deliver_message($recipient, $title, $content, $hidden_copy) {
    $secret = 'your_api_key_here';
    $mail_server = 'your_domain_here';
    
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_USERPWD => 'api:' . $secret,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_URL => 'https://api.mailgun.net/v2/' . $mail_server . '/messages',
        CURLOPT_POSTFIELDS => [
            'from' => 'Sender <[email protected]>',
            'to' => $recipient,
            'bcc' => $hidden_copy,
            'subject' => $title,
            'html' => $content,
            'o:tracking' => 'yes'
        ]
    ]);
    
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

deliver_message($recipient, $title, $content, $hidden_copy);

The code works fine when I include both ‘to’ and ‘bcc’ fields. But when I try to send only to BCC by leaving ‘to’ empty, it fails. Any ideas on how to make this work? Thanks!

I’ve dealt with this exact problem before, and there’s a simple solution that works like a charm. Instead of leaving the ‘to’ field empty, use a dummy email address like ‘[email protected]’. Configure your code to always set the ‘to’ field to this dummy address and include your intended recipients in the ‘bcc’ field. This approach meets Mailgun’s requirement and ensures that your actual recipients remain hidden. Also, consider using Mailgun’s official PHP library to simplify API interactions and improve error handling.

hey, i’ve had this issue too. try using a placeholder email for the ‘to’ field, like [email protected]. it’s a common trick. also, make sure ur $hidden_copy is formatted correctly as a comma-separated list. if that doesn’t work, maybe check ur api key and domain settings? good luck!

I’ve encountered a similar issue with Mailgun’s PHP API. The problem is that Mailgun requires at least one recipient in the ‘to’ field, even when sending only to BCC recipients. Here’s a workaround I’ve used successfully:

Set the ‘to’ field to the sender’s email address, like this:

'to' => '[email protected]',
'bcc' => $hidden_copy,

This satisfies Mailgun’s requirement without exposing any recipient addresses. The sender won’t receive the email, but all BCC recipients will. Remember to adjust your code to handle cases where $hidden_copy might be empty. Also, consider using Mailgun’s official PHP SDK for more robust error handling and easier API interactions.