const { google } = require('googleapis');
const base64 = require('base-64');
const utf8 = require('utf8');
async function gmailSendMessage() {
try {
const auth = await google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/gmail.send'],
});
const service = google.gmail({ version: 'v1', auth });
const message = new Buffer.from('This is automated draft mail');
const encodedMessage = base64.encode(utf8.encode(message.toString()));
const emailMessage = [
'To: gduser1@workspacesamples.dev',
'From: gduser2@workspacesamples.dev',
'Subject: Automated draft',
'',
encodedMessage,
].join('\r\n');
const createMessage = {
raw: base64.encode(utf8.encode(emailMessage)),
};
const sendMessage = await service.users.messages.send({
userId: 'me',
requestBody: createMessage,
});
console.log(`Message Id: ${sendMessage.data.id}`);
return sendMessage.data;
} catch (error) {
console.error(`An error occurred: ${error.message}`);
return null;
}
}
if (require.main === module) {
gmailSendMessage();
}