Problems with BCC in PHPMailer when formatting MIME messages for Gmail API

I’m having trouble with BCC recipients when using PHPMailer to format MIME messages for the Gmail API. Here’s what’s happening:

  • TO and CC addresses work fine
  • BCC addresses are not receiving the email
  • ‘undisclosed-recipients’ is missing from the sent message header

I’m not using PHPMailer to send the email, just to format the MIME message. Then I pass the raw message to the Gmail API for sending.

Here’s a simplified version of my code:

$mail = new PHPMailer;
$mail->isSMTP();
$mail->IsHTML(true);
$mail->setFrom('[email protected]', 'Sender');
$mail->addAddress('[email protected]', 'Recipient');
$mail->addBCC('[email protected]', 'BCC Recipient');
$mail->Subject = 'Test Email';
$mail->Body = '<p>This is a test</p>';

$mail->preSend();
$mime = $mail->getSentMIMEMessage();

$gmailMessage = new Google_Service_Gmail_Message();
$gmailMessage->setRaw(base64_encode($mime));
$gmailService->users_messages->send('me', $gmailMessage);

Has anyone else run into this issue? Any ideas on how to fix it?

hey man, i had similar issues. try adding bcc recipients directly to the raw message before encoding. smth like:

$mime = $mail->getSentMIMEMessage();
$mime = str_replace(‘To: [email protected]’, ‘To: undisclosed-recipients:;’ . “\r\n” . ‘Bcc: [email protected]’, $mime);

then base64 encode and send. Hope it helps!

I’ve dealt with this exact problem before. The issue stems from how PHPMailer handles BCC when formatting for external APIs. Here’s what worked for me:

Instead of using addBCC(), try setting the Bcc header manually after generating the MIME message. Something like this:

$mime = $mail->getSentMIMEMessage();
$mime = “Bcc: [email protected]\r\n” . $mime;

$gmailMessage->setRaw(base64_encode($mime));

This method preserves the BCC functionality while keeping recipients hidden. Make sure to test thoroughly, especially with multiple BCC addresses. Also, double-check your Gmail API permissions to ensure you have the necessary scope for sending emails.

If you’re still having issues, consider using the Gmail API’s native methods for handling BCC instead of relying on PHPMailer’s implementation.

I’ve encountered this issue before when working with PHPMailer and the Gmail API. The problem lies in how PHPMailer handles BCC recipients while generating the MIME message. A workaround I’ve found effective is to manually inject the BCC headers after the MIME message is generated. First, generate the MIME message without BCC recipients, then manually add the BCC headers to the message, base64 encode the updated message, and finally send it via the Gmail API. This approach ensures the BCC recipients are included without revealing their privacy. Testing thoroughly with multiple BCC recipients is advisable to avoid interfering with other functionalities.