我正在尝试使用gmail api使用laravel发送邮件。
我发送的消息是
$text = 'From: '.$from.'
To: '.$to.'
Subject:'.$subject.'
'.$body.'';
$encoded_message = rtrim(strtr(base64_encode($text), '+/', '-_'), '=');
$message->setRaw($encoded_message);
$message = $service->users_messages->send($userId, $message);
我尝试编辑标签 ID 和线程 ID,如下所示,
$text = 'labelIds: ':'.SENT.'
'From: '.$from.'
To: '.$to.'
Subject:'.$subject.'
'.$body.'';
这给出了语法错误。如何为 gmail-api 添加标签 ID 和线程 ID?
编辑1
发送后我的消息是,
object(Google_Service_Gmail_Message)#1048 (14){
[
"historyId"
] => string(4) "4171" [
"id"
] => string(16) "15270b9c7b867bab" [
"internalDate"
] => string(13) "1453590169000" [
"labelIds"
] => NULL
这是creating a new threadId
,我需要sent it as reply
的地方。如何send the mail with same threadId
?
您现在可能已经解决了这个问题,但是我遇到了类似的问题,并在寻找解决方案时发现了这个线程,因此我想分享我使用的方法,以防其他人需要它。
基于 Gmail 的 API 规范
1.请求的线程 ID 必须在随请求一起提供的消息或草稿消息中指定。
2.引用和回复标头必须按照 RFC 2822 标准进行设置。
3.主题标题必须匹配。
数字 2 对我来说很复杂,因为我尝试手动设置引用和回复标题。我的想法是从同一线程中的最后一条消息中获取它们,但 API 没有返回这些标头,我设置的内容显然不准确。然后,按照这个线程 MIME 标头未通过 Gmail API 制作,我删除了所有其他标头,仅设置了 threadId 和匹配的主题。
我使用 PHPMailer 库来格式化 mime 字符串,而不是手动进行(它减少了出错的可能性)。使用composer,你只需要在composer.json的require部分添加"phpmailer/phpmailer":"~5.2"。这是我的解决方案:
$thread = $gmail->users_threads->get($user_id,$threadId);
if($thread) {
$opt_param['threadId'] = $threadId;
$thread_messages = $thread->getMessages($opt_param);
if($thread_messages) {
$messageId = $thread_messages[0]->getId();
$messageDetails = $gmail->users_messages->get($messageId);
// get the subject here from the headers of $messageDetails. You will use it below as $subject.
}
}
$message = new Google_Service_Gmail_Message();
$mail = new PHPMailer();
$mail->From = 'YOUR_EMAIL'; // I tried with 'me' here, but PHPMailer doesn't consider it valid, so it can either be the email or userId
$mail->FromName = 'YOUR_NAME';
$mail->addAddress('RECIPIENT_EMAIL'); // Make sure this is the same as the email in the message you reply to
$mail->Subject = $subject; // the subject from $messageDetails from above
$mail->Body = $body;
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$raw = rtrim(strtr(base64_encode($mime), '+/', '-_'), '='); // web safe base64 encode
$message->setRaw($raw); // You set the thread id to your message object now, separately from the other headers
$message->setThreadId($threadId);
$gmail->users_messages->send($user_id, $message);
上面使用的变量:
$gmail - your instance of Google_Service_Gmail;
$user_id - the id of the authenticated user (can be 'me' for the current logged in user);
$threadId - the thread under which you want to send your email
希望这是有帮助的。