关于angularjs:仅使用令牌发送带有Gmail API的电子邮件?

Sending an email with Gmail's API using only a token?

我正在尝试使用Google的API发送电子邮件。我有一个由AngularJS驱动的Web应用程序,其中用户使用oauth2使用其Google帐户(通过passport.js)登录。一个新的访问令牌将写入他们在我的数据库中的帐户。他们的google用户ID也将写入他们的帐户。我希望用户能够仅使用其用户ID和访问令牌通过HTTP请求发送电子邮件。我正在使用Postman发出一些测试请求,但我不断收到此错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
 "error": {
   "errors": [
      {
       "domain":"global",
       "reason":"insufficientPermissions",
       "message":"Insufficient Permission"
      }
    ],
   "code": 403,
   "message":"Insufficient Permission"
  }
}

我正在使用以下链接发出POST请求:

1
https://content.googleapis.com/gmail/v1/users/106xxxxxxxxxxx/messages/send

标题中有:

1
2
Authorization: Bearer yaxx._wxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Content-Type: application/json

我的身体:

1
2
3
{
"raw":"test"
}

我使用这种方法间歇性地收到了一些电子邮件,但是我似乎无法确定地重新创建成功的请求。 Google的文档让我有些困惑。是否需要显式授予访问权限,如本页底部的示例所示?


您提到的access token必须出现在发送邮件的POST-请求中。 Oauth2-procotol指示您需要传递标题Authorization: Bearer <ACCESS_TOKEN>或参数access_token=<ACCESS_TOKEN>

raw的值也必须是有效的以base64编码的rfc822邮件。 JavaScript中的示例可能如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Base64-encode the mail and make it URL-safe
// (replace all"+" with"-" and all"/" with"_")
var encodedMail = btoa(
     "Content-Type: text/plain; charset="UTF-8"\
" +
     "MIME-Version: 1.0\
" +
     "Content-Transfer-Encoding: 7bit\
" +
     "Subject: Subject of the mail\
" +
     "From: [email protected]\
" +
     "To: [email protected]\
\
" +

     "This is where the mail text will go"
    ).replace(/\\+/g, '-').replace(/\\//g, '_');

这将导致在请求正文中用作raw的字符串。

邮递员中的请求如下所示:

1
2
3
4
5
POST https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token=<ACCESS_TOKEN>

{ // The encoded mail from the example above.
"raw":"Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJVVEYtOCIKTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogN2JpdApTdWJqZWN0OiBTdWJqZWN0IG9mIHRoZSBtYWlsCkZyb206IHNlbmRlckBnbWFpbC5jb20KVG86IHJlY2lldmVyQGdtYWlsLmNvbQoKVGhpcyBpcyB3aGVyZSB0aGUgbWFpbCB0ZXh0IHdpbGwgZ28="
}

您还需要为Content-Type标题提供值application/json。请注意,您不必使用userId。提供me将使Google自动使用与提供的访问令牌关联的用户。

还请确保您已请求Passport的足够权限scopehttps://mail.google.com/将起作用。