gmail - Google GMail API - users.messages.import() 不在收件箱中 为什么?
问题描述
我正在使用 GMAil API 直接导入消息当我查看 GMail 用户帐户(浏览器 GMail 应用程序)时,我可以看到在所有邮件中收到的消息,但在收件箱中看不到
Google GMail API 状态:Users.messages.import()
仅将邮件导入此用户的邮箱,使用标准的电子邮件传递扫描和分类,类似于通过 SMTP 接收。不发送消息
由于邮件在那里,我无法从 Mail.app (OSX) 或 Outlook (MS) 中获取它,因为它不被视为新邮件......是真的吗?无论如何要解决这个问题?
这是我用来导入新消息的功能
unction gMailInserMessage (sender_name, sender_email, msg_text) {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const jwtClient = new google.auth.JWT(
postoffice_key.client_email,
null,
postoffice_key.private_key,
_.values(config_key.scopes.postoffice),
config_key.contact_email // subject (or sub) impersonated user
);
return jwtClient.authorize().then(tokens => {
// Obtain a new gmail client, making sure we pass along the auth client
const gmail = google.gmail({
version: 'v1',
auth: jwtClient
});
const subject = ' CONTACT ';
const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;
const messageParts = [
'From: ' + sender_name + '<' + sender_email + '>',
'To: Contact Box <' + config_key.contact_email + '>',
'Content-Type: text/html; charset=utf-8',
`Subject: ${utf8Subject}`,
'',
'A new contact message just to say hello.',
'So... <b>Hello!</b> ❤️'
];
const message = messageParts.join('\n');
// The body needs to be base64url encoded.
const encodedMessage = Buffer.from(message)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
//Make an authorized request to import a User Messages
return gmail.users.messages.import({
userId: 'me',
resource: {
raw: encodedMessage
}
});
}).then(res => {
// console.log('RES: ', res)
return res.data;
});
}
这是我从请求中得到的响应
RES: { status: 200,
statusText: 'OK',
headers:
{ 'cache-control': 'no-cache, no-store, max-age=0, must-revalidate',
pragma: 'no-cache',
expires: 'Mon, 01 Jan 1990 00:00:00 GMT',
date: 'Sun, 27 May 2018 10:00:12 GMT',
etag: '"Mr5Glppow16hK9x9KiNoxDVbWS4/98vlvSafvJVr4JD8evQ2SHoRCuQ"',
vary: 'Origin, X-Origin',
'content-type': 'application/json; charset=UTF-8',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block',
server: 'GSE',
'alt-svc': 'hq=":443"; ma=2592000; quic=51303433; quic=51303432; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="43,42,41,39,35"',
connection: 'close',
'transfer-encoding': 'chunked' },
config:
{ adapter: [Function: httpAdapter],
transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: 2147483648,
validateStatus: [Function],
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/31.0.2 (gzip)',
Authorization: 'Bearer ya29.GoEByAXKR5aJgJanVZebkHwurMcOn6FB4ymK9BZqmi_0K0uMPK_1AJAL-EQa0ajz1OBDoJE1cWAyRzprOYbDnJrnpusrPfFSL7HuBmMqXFULxEKECedOb5pKwkTFA9CffIZS1Fg1uwuGcsgUqO98XOkYeRh9ul7icvBpuzUgaML0SVJN',
'Content-Length': 397 },
method: 'post',
url: 'https://www.googleapis.com/gmail/v1/users/me/messages/import',
paramsSerializer: [Function],
data: '{"raw":"RnJvbTogTW1lIElzYWJlbGxlIER1Zm91ciA8ZHVmb3VyaXNhYmVsbGVAb3JhbmdlLmZyPgpUbzogQ29udGFjdCBCb3ggPHl2ZXNkdWZvdXJAbGVjaG9yb2Rlc2NoYXJlbnRlcy5vcmc-CkNvbnRlbnQtVHlwZTogdGV4dC9odG1sOyBjaGFyc2V0PXV0Zi04Ck1JTUUtVmVyc2lvbjogMS4wClN1YmplY3Q6ID0_dXRmLTg_Qj84SitrbUNCRFQwNVVRVU5VSVBDZnBKZz0_PQoKVGhpcyBpcyBhIE5FVyBORVcgbWVzc2FnZSBqdXN0IHRvIHNheSBoZWxsby4KU28uLi4gPGI-SGVsbG8hPC9iPiAg8J-kmOKdpO-4j_CfmI4"}',
params: { internalDateSource: 'dateHeader' } },
解决方案
解决了尝试使用 Firebase 功能处理站点联系表时出现的所有问题。
1 - 使用 GCP,在我的 Firebase 项目中,我创建了一个名为“邮局”的服务帐户,具有域范围委派,将 JSON 格式的凭据下载到函数/postoffice-key.json 2 - 我为项目启用了 GMail API 3 -我在另一个函数/config-key.json 中处理范围和电子邮件地址
4- 在我的 GSuite 管理控制台(安全>高级设置>管理 API 客户端访问)中,我从 postoffice-key.json 文件中添加了具有授权范围的 clientId
5 - 我写了一个新的 Firebase HTTPS 函数: newContactMessage()
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const { google } = require('googleapis');
const path = require('path');
const _ = require('lodash');
var Buffer = require('buffer/').Buffer // note: the trailing slash is important!
// KEY FILES
const postoffice_key = require('./postoffice-key.json');
const config_key = require('./config-key.json');
function gMailInsertContactMessage (sender_name, sender_email, msg_text) {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const jwtClient = new google.auth.JWT(
postoffice_key.client_email,
null,
postoffice_key.private_key,
_.values(config_key.scopes.postoffice),
config_key.admin_email // subject (or sub) impersonated user
);
return jwtClient.authorize().then(tokens => {
// Obtain a new gmail client, making sure we pass along the auth client
const gmail = google.gmail({
version: 'v1',
auth: jwtClient
});
const subject = ' CONTACT ';
const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;
const messageParts = [
'From: "Administrator" <' + config_key.admin_email + '>',
'To: "Contact Box" <' + config_key.contact_email + '>',
'Reply-To: "' + sender_name + '" <' + sender_email + '>',
'Content-Type: text/html; charset=utf-8',
'MIME-Version: 1.0',
`Subject: ${utf8Subject}`,
'',
'<h2>MESSAGE</h2>',
'<p>' + msg_text + '</p>'
];
const message = messageParts.join('\n');
// The body needs to be base64url encoded.
const encodedMessage = Buffer.from(message)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
//Make an authorized request to import a User Messages
return gmail.users.messages.send({
userId: 'me',
resource: {
raw: encodedMessage
}
});
}).then(res => {
// console.log('RES: ', res)
return res.data;
});
}
// FIREBASE HTTP FUNCTIONS ==================
exports.newContactMessage = functions.https.onRequest((req, res) => {
const sender_name = 'Mrs Jenny Doe'
const sender_email = 'jenny.doe@example.com'
const sender_msg = 'Hello, how are you overthere ?'
gMailInsertContactMessage(sender_name, sender_email, sender_msg).then((res) => {
return { status: 200, infos: res };
}, error => {
return {status: error.status, infos: error.message};
}).then(response => {
return res.send(response);
}).catch(console.error);
});
测试要求:
curl -v https://us-central1-myproject.cloudfunctions.net/newContactMessage
Firebase 函数返回:
{"status":200,"infos"
{"id":"163a5738080e3ee9","threadId":"163a5738080e3ee9","labelIds":["SENT"]}}
在我计算机上的 Mail.app 中,我可以看到 From:作为项目所有者(管理员)To:作为联系人框(contact@mysite.org 和回复:作为联系表发件人电子邮件......容易回复..!和留言内容!
希望这有帮助...(我应该编辑问题标题吗?)
推荐阅读
- excel - 如何输入用户路径并直接分配给命令提示符
- java - Vertx OAuth2AuthHandler 与多个提供商(Facebook、Google 或任何)
- arrays - golang中具有整数和nil值的数组?
- animation - Adobe Animate gotoAndPlay 鼠标滚动
- python - 如何从 MATLAB 中返回的 python 数据类型获取数据?
- python - 使用 CAD 查看器打印预设视图(无需 AutoCAD)
- python - 为 Mac pyodbc 安装 ODBC 驱动程序
- excel - 如何纠正错误“没有为一个或多个参数指定值”
- python - today.strftime('%Y_%m_%d') - 不返回当前日期
- php - Laravel 5.6:使用迁移创建数据库模式