我想使用 Gmail API 从我在 nodejs 服务器中的 G-Suite 帐户发送一封电子邮件。我知道凭据没问题,因为我从 G-Suite 获取消息/标签没有问题。
这是我的代码:
const {GoogleAuth} = require('google-auth-library');
async sendMessage(to, from, subject, message) {
let raw = makeBody(to, from, subject, message);
let url = `https://www.googleapis.com/gmail/v1/users/${<MyEmail>}/messages/send`
let option = {
method: 'POST',
headers: {
'Content-Type': 'message/rfc822',
},
body: raw,
};
let client = await getClient()
client.request({url, option}, (res, err) => {
if (err) {
console.log('error', err);
} else {
console.log('res');
}
});
}
async getClient() {
try {
let auth = new GoogleAuth({
credentials: {
client_email: <clientEmail>,
private_key: <privateKey>,
},
scopes: [
"https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.send"],
clientOptions: {subject: <myEmail>}
});
const client = await auth.getClient();
if (client)
return client
} catch (e) {
console.log('error accured while getClient', e);
return e;
}
}
我将send、compose和modify的范围添加到 Admin Google,不幸的是我收到了这个 400 bad request:
error [
{
domain: 'global',
reason: 'invalidArgument',
message: 'Invalid id value'
}
]