Trying to send an email using a service account with role owner within my project. I keep getting a 400 error that says Precondition check failed.
const sendEmail = async () => {
const auth = new google.auth.GoogleAuth({
keyFile: "gmail.json", //the key file
scopes: "https://www.googleapis.com/auth/gmail.send",
});
const authClientObject = await auth.getClient();
const gmail = google.gmail({version:"v1", auth: authClientObject})
// Compose the email
const email = 'To: [email protected]\r\n' +
`Cc: [email protected]\r\n` +
'Subject: CUSTOM DONATION ALERT\r\n\r\n' +
'blablabla\r\n';
// Encode the email in base64 format
const base64EncodedEmail = Buffer.from(email).toString('base64');
// Send the email
gmail.users.messages.send({
userId: serviceAccountEmail,
resource: {
raw: base64EncodedEmail,
},
}, (err, res) => {
if (err) {
console.error('Error sending email:', err);
return;
}
console.log('Email sent:', res.data);
});
}
Normally occurs when you are using a service account and have not properly configured domain wide delegation within your google workspace account.
I can also see you have not denoted which user in your workspace account the service account should delignate as.