如何使用Gmail API发送回复邮件
我正在使用Gmail API发送一封电子邮件,发送成功。我想知道如何用php回复那个已经发送的人。
在此附上我的发送代码:
$line = "
";
$strMailContent = $message;
$strMailTextVersion = strip_tags($strMailContent, '');
$strRawMessage = "";
$boundary = uniqid(rand(), true);
$subjectCharset = $charset = 'utf-8';
$strToMail = $to;
$strSubject = $subject;
$strRawMessage .= 'To: ' . ($strToMail) . "
";
if(!empty($_POST['cc']) || !empty($_POST['bcc'])){
$cc = $_POST['cc'];
$bcc = $_POST['bcc'];
$strRawMessage .= "Cc: $cc". $line;
$strRawMessage .= "Bcc: $bcc". $line;
}
$strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=
";
$strRawMessage .= 'MIME-Version: 1.0' . "
";
$strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "
";
$filePath = $file_tmp_name;
$mimeType = 'text/plain; charset="UTF-8" ';
$fileName = $file_name;
$fileData = base64_encode(file_get_contents($filePath));
$strRawMessage .= "
--{$boundary}
";
$strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "
";
$strRawMessage .= 'Content-Description: ' . $fileName . ';' . "
";
$strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "
";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "
";
$strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "
") . "
";
$strRawMessage .= '--' . $boundary . "
";
$strRawMessage .= $strMailContent;
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$base64 = base64_encode($mime);
$data = '{ "raw" : "'.$mime.'" }';
$send = Qassim_HTTP(1, $url, $header, $data);
在这里,我将收件人地址作为已发送人员邮件ID传递,并且主题已是已使用的主题。
如何更改此代码以发送回复。请帮帮我
解决方案
您需要传递要回复的邮件的线程ID,并为新邮件设置相同的主题。我更喜欢使用某个库来生成消息的原始字符串,而不是手动编写,以便将出错的可能性降至最低。以下是使用PHPMailer的示例。
$gmail = new Google_Service_Gmail($client);
$message = new Google_Service_Gmail_Message();
$optParam = array();
$referenceId = '';
$thread = $gmail->users_threads->get($userId, $threadId);
$optParam['threadId'] = $threadId;
$threadMessages = $thread->getMessages($optParam);
$messageId = $threadMessages[0]->getId();
$messageDetails = $this->getMessageDetails($messageId); //omitted for simplicity: returns prepared message data.
$messageDetails = $messageDetails['data'];
$subject = $messageDetails['headers']['Subject'];
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = $from_email;
$mail->FromName = $from_name;
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$raw = $this->Base64UrlEncode($mime); //omitted for simplicity: Encodes the data in base 64 format for sending.
$message->setRaw($raw);
$message->setThreadId($threadId);
$response = $gmail->users_messages->send($userId, $message);
userId
是登录用户的ID,而threadId
是您要回复的邮件的主题ID。
我在使用Google的PHPSDK时遇到了很多困难,而且缺乏合适的示例,所以我编写了一个涵盖Gmail API大部分函数的PHP包装器。它涵盖了上面的解释,如果你深入研究它,你会发现上面的例子中省略的逻辑。您可以找到here。
相关文章