[英]Send mail using Gmail API with service account
这是我的准系统代码。 我想发送一个 email 作为我域的用户之一。 email 可能每次调用都不同。
const { google } = require('googleapis');
function makeBody(to, from, subject, message) {
const str = [
'Content-Type: text/plain; charset="UTF-8"\n',
'MIME-Version: 1.0\n',
'Content-Transfer-Encoding: 7bit\n',
'to: ', to, '\n',
'from: ', from, '\n',
'subject: ', subject, '\n\n',
message,
].join('');
return Buffer.from(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
}
class MailProvider {
gmail = google.gmail({
version: 'v1',
auth: new google.auth.GoogleAuth({
keyFile: '../../assets/secrets/google.json', // See below
scopes: [
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.addons.current.action.compose',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.send',
],
}),
});
async sendMail(sendAs, sendTo) {
return this.gmail.users.messages.send({
userId: sendAs,
requestBody: {
raw: makeBody(sendTo, sendAs, 'Test subject', 'Test body'),
},
}).catch(console.error);
}
}
new MailProvider().sendMail('noreply@mydomain.cz', 'akxe@seznam.cz');
审查google.json
:
{
"type": "service_account",
"project_id": "firm-aria-ID",
"private_key_id": "ID",
"private_key": "-----BEGIN PRIVATE KEY-----\n...key...\n-----END PRIVATE KEY-----\n",
"client_email": "rita-sm@firm-aria-ID.iam.gserviceaccount.com",
"client_id": "ID",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/rita-sm%40firm-aria-ID.iam.gserviceaccount.com"
}
我收到failedPrecondition
错误。 我不知道该怎么办了……我在这呆了一整天……
错误:
{
// ...
code: 400,
errors: [
{
message: 'Precondition check failed.',
domain: 'global',
reason: 'failedPrecondition'
}
]
}
您不能使用服务帐户发送电子邮件。 您需要使用 3 条腿 oauth 并代表最终用户发送电子邮件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.