我正在尝试使用laravel使用gmail api发送邮件。
我发送的消息是
$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添加labelid和线程ID?
EDIT1
发送后我的留言是,
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
?
答案 0 :(得分:1)
你现在可能已经解决了这个问题,但我遇到了类似的问题并在寻找解决方案时发现了这个问题,所以我想分享我用过的方法以防其他人需要它。
基于Gmail的API规范
1.必须在您提供请求的Message或Draft.Message上指定请求的threadId。
2.必须根据RFC 2822标准设置References和In-Reply-To标头 3.主题标题必须匹配。
数字2对我来说很复杂,因为我试图手动设置References和In-Reply-To标头。我的想法是从同一个帖子中的最后一条消息中获取它们,但API没有返回那些标题,我设置的内容显然是不准确的。然后,在此线程MIME Headers Not Making it Through Gmail API之后,我删除了所有其他标头,并仅设置了threadId和匹配的主题。
我使用PHPMailer库来格式化mime字符串,而不是手动执行(它减少了出错的可能性)。使用作曲家,你只需要添加" phpmailer / phpmailer":" ~5.2"在你的composer.json的require部分。 这是我的解决方案:
$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
希望这有用。