Open DevCEDTeam opened 1 year ago
Set up a new project:
npm init -y
npm install googleapis google-auth-library
Set up OAuth 2.0 credentials:
credentials.json
.credentials.json
file to your project directory.Write the code:
sendEmail.js
, in your project directory.sendEmail.js
file in a text editor.Add the following code to import the required modules and set up the Gmail API client:
const { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
async function sendEmail() {
// Load credentials from the JSON file
const credentials = require('./credentials.json');
// Configure the OAuth2 client
const client = new OAuth2Client(credentials.client_id, credentials.client_secret, 'urn:ietf:wg:oauth:2.0:oob');
client.setCredentials({
refresh_token: credentials.refresh_token,
access_token: credentials.access_token,
});
// Create a new Gmail API client
const gmail = google.gmail({ version: 'v1', auth: client });
// Construct the email message
const email = {
to: 'recipient@example.com',
subject: 'Test Email',
message: 'Hello, this is a test email.',
};
// Send the email using the Gmail API
const res = await gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: createEmail(email),
},
});
console.log('Email sent. Message ID:', res.data.id);
}
// Helper function to create the email message
function createEmail({ to, subject, message }) {
const emailLines = [];
emailLines.push(`To: ${to}`);
emailLines.push('Content-Type: text/html; charset=utf-8');
emailLines.push('MIME-Version: 1.0');
emailLines.push(`Subject: ${subject}`);
emailLines.push('');
emailLines.push(message);
return Buffer.from(emailLines.join('\n')).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
}
// Call the sendEmail function
sendEmail().catch(console.error);
``
Update the email details:
sendEmail
function, update the to
, subject
, and message
variables to specify the recipient's email address, the subject of the email, and the content of the email message, respectively.Run the code:
sendEmail.js
file.node sendEmail.js
By following these steps, you should be able to use the provided Node.js code snippet to send an email using the Gmail API and the Google OAuth 2.0 client library. Make sure to replace the placeholders with your actual values and customize the email details as per your requirements.
Implement Gmail API with Google OAuth 2.0 Client. Step-by-step instructions on how to use a Node.js code snippet to send an email using the Gmail API and the Google OAuth 2.0 client library: