当使用PHPMailer为Gmail API格式化MIME邮件时,如何发送到BCC地址


How to send to BCC address when using PHPMailer to format MIME message for Gmail API?

我正在使用PHPMailer构建电子邮件。我使用PHPMailer只是为了MIME邮件格式,而不是发送。

然后,我从PHPMailer对象中提取原始消息,然后将其传递给Gmail API进行处理。

//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->IsHTML(true);
//Disable SMTP debugging
// 0 = off (for production use)
$mail->SMTPDebug = 0;
//Set who the message is to be sent from
$mail->setFrom("fromaddress@domain.com", "From Name");
//Set an alternative reply-to address
$mail->addReplyTo("replyaddress@domain.com", "Reply Name");
//Set to address
$mail->addAddress("address@domain.com", "Some Name");
//Set CC address
$mail->addCC("ccaddress@ccdomain.com", "Some CC Name");
//Set BCC address
$mail->addBCC("bccaddress@ccdomain.com", "Some BCC Name");
//Set the subject line
$mail->Subject = "Test message";
//Set the body
$mail->Body = file_get_contents("/messagestore/some.html");
//Attach a file
$mail->addAttachment("/messagestore/some.pdf","some.pdf","base64","application/pdf");
//generate mime message
$mail->preSend();
//get the mime text
$mime = $mail->getSentMIMEMessage();
//do the google API dance
$newMailMessage = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$newMailMessage->setRaw($data);
$gmailService = new Google_Service_Gmail($google_client);
$gmailService->users_messages->send('me', $newMailMessage);

根据PHPMailer文档,CC和BCC仅用于在Win32环境中发送。

然而,我的MIME格式的邮件通过Gmail API成功传输到"to"answers"CC"地址,但不是"BCC"地址。

总之,当我使用此代码发送电子邮件并向Gmail API提供"密件抄送"地址时,我不会在发送的邮件标题中看到"未丢失的收件人",并且邮件不会发送到密件抄送地址。

当我使用gmail web界面发送电子邮件,并在那里提供"密件抄送"地址时,我会在发送的邮件标题中看到"未公开的收件人",并且邮件传输到密件抄送地址。

有人知道这个问题的解决方法吗?

PHPMailer将在内部跟踪密件抄送收件人,如果您要使用PHPMailler发送邮件,它将在SMTP信封中指定密件抄送的收件人。

但是,当您从PHPMailer提取原始消息时,您将丢失PHPMailer正在跟踪的内部收件人列表。原始消息不包括密件抄送信息。To:Cc:报头将包括适当的接收者,GMAIL API可能使用这些报头来推断预期的接收者。

若要添加BCC收件人,您需要在发送邮件之前使用GMAIL API添加这些收件人。

您没有提供GMAIL API代码,但它可能遵循以下大纲:

$message = new Message();
# construct message using raw data from PHPMailer
$message->setSubjectBody(...);
$message->setTextBody(...);
$message->setHtmlBody(...);
# *** add the BCC recipients here ***
$message->addBcc("secret.recipient@google.com");
# send the message
$message->send();

对于任何发现这个问题但没有使用Gmail api发送的人,只使用PhpMailer构建原始MIME消息:

如果您设置$phpMailer->isMail()(是的,这是一个setter),它将在原始MIME消息中包含BCC:。

如果phpMailer对象设置为SMTP或mail方法,我想这没有什么区别,因为您不会使用它来实际发送电子邮件。

只需添加

$mail->addBCC('bcc@example.com');