Search code examples
phpimapbccphp-imap

PHP imap_append with BCC


I'm handling a mailbox for an app, and after sending an e-mail, I'd like to append it in a "Sent" mailbox, and to be able to retrieve recipients (to, cc and bcc).

This works great with the following code...

$envelope = imap_mail_compose([
    'subject' => 'test',
    'from' => '[email protected]',
    'to' => '[email protected]',
    'cc' => '[email protected]',
    'bcc' => '[email protected]'
], $body);

imap_append($imap, '{ssl0.ovh.net:xxx/ssl}SENT', $envelope);

...except for the bcc. If I retrieve the e-mail headers after appending, it seems there is no bcc, whereas there should be! (I can retrieve to and cc addresses).

I can't find why. Did I make a mistake? Did I misunderstand something?

Edit: ok, with imap_mail_compose bcc remains invisible (so why can we add a "bcc" parameter, if it is not used?). So, there is no way to append the Bcc addresses?


Solution

  • Ok, trick found.

    I create the global message string using imap_mail_compose, like below.

    Then, I append the Bcc addresses into that string:

    // The Bcc string, from an array
    $bcc = implode(',', $data['bcc']);
    
    // create the global message string
    $envelopeStr = imap_mail_compose($data, $body);
    
    // Appending the Bcc addresses manually
    if (!empty($bcc)) {
        // Putting the Bcc just before the main recipients
        // There will be a "To:" parameter for sure, we could have used "Subject:" too
        $pos = strpos($envelopeStr , "To:");
        // Adding the string
        if ($pos !== false) {
            $bccStr = "Bcc: " . $bcc . "\r\n";
            $envelopeStr = substr_replace($envelopeStr , $bccStr, $pos, 0);
        }
    }