JSFiddle - React, Tailwind, and code Playground
by Alex Cowan
HTML
<script src="https://apis.google.com/js/api.js"></script>
JavaScript
// Define your Gmail API client ID
const CLIENT_ID = '737018927349-moqls2i9c7dcilulag8ejqpcfv0b0ma9.apps.googleusercontent.com';
// Define the Gmail API scope for sending emails
const GMAIL_API_SCOPE = 'https://www.googleapis.com/auth/gmail.send';
// Initialize the Gmail API client
gapi.load('client:auth2', () => {
gapi.client.init({
clientId: CLIENT_ID,
scope: GMAIL_API_SCOPE,
});
// Authenticate the user
gapi.auth2.getAuthInstance().signIn().then(() => {
// Create a message to send
const emailMessage = {
to: '[email protected]',
subject: 'Your Subject Here',
message: 'Your email message content here.',
};
// Send the email
sendEmail(emailMessage);
});
});
// Function to send an email using the Gmail API
function sendEmail({ to, subject, message }) {
const email = [
'Content-Type: text/plain; charset="UTF-8"\r\n',
'MIME-Version: 1.0\r\n',
`To: ${to}\r\n`,
`Subject: ${subject}\r\n\r\n`,
message,
].join('');
const base64EncodedEmail = btoa(email);
gapi.client.gmail.users.messages.send({
userId: 'me',
resource: {
raw: base64EncodedEmail,
},
}).then((response) => {
console.log('Email sent:', response);
}).catch((error) => {
console.error('Error sending email:', error);
});
}