I’m trying to send emails through Gmail API using native NodeJS HTTPS module and getting a 400 error saying recipient address is required. Here’s my approach:
var message = (
"Content-Type: text/plain; charset=\"UTF-8\"\n" +
"MIME-Version: 1.0\n" +
"to: [email protected]\n" +
"from: \"My App\" <[email protected]>\n" +
"subject: Test Message\n\n" +
"This is the email content"
);
function deliverEmail(accessToken) {
return new Promise((resolve, reject) => {
var encodedMessage = Buffer.from(message).toString('base64');
var urlSafeEncoded = encodedMessage.replace(/\+/g, '-').replace(/\//g, '_');
var requestBody = {
"raw": urlSafeEncoded
};
var requestOptions = {
hostname: 'www.googleapis.com',
path: '/gmail/v1/users/me/messages/send',
method: 'POST',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
}
};
const request = https.request(requestOptions, (response) => {
let responseData = '';
response.on('data', (chunk) => {
responseData += chunk;
});
response.on('end', () => {
console.log(responseData);
});
});
request.on('error', (error) => {
console.error(error);
});
request.write(JSON.stringify(requestBody));
request.end();
});
}
The base64url encoding seems correct because it works in the API explorer, but my POST request structure must be wrong. What’s the proper way to format the request body for Gmail API without using client libraries?