Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Client ID and API key from the Developer Console
- const CLIENT_ID = 'YOUR_CLIENT_ID';
- const API_KEY = 'YOUR_API_KEY';
- // Array of API discovery doc URLs for APIs used
- const DISCOVERY_DOCS = ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'];
- // Authorization scopes required by the API
- const SCOPES = 'https://www.googleapis.com/auth/gmail.modify';
- let authorizeButton = document.getElementById('authorize_button');
- let cleanupButton = document.getElementById('cleanup_button');
- function handleClientLoad() {
- gapi.load('client:auth2', initClient);
- }
- function initClient() {
- gapi.client.init({
- apiKey: API_KEY,
- clientId: CLIENT_ID,
- discoveryDocs: DISCOVERY_DOCS,
- scope: SCOPES
- }).then(function () {
- // Listen for sign-in state changes
- gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
- // Handle initial sign-in state
- updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
- authorizeButton.onclick = handleAuthClick;
- cleanupButton.onclick = cleanupInbox;
- });
- }
- function updateSigninStatus(isSignedIn) {
- if (isSignedIn) {
- authorizeButton.style.display = 'none';
- cleanupButton.disabled = false;
- } else {
- authorizeButton.style.display = 'block';
- cleanupButton.disabled = true;
- }
- }
- function handleAuthClick() {
- gapi.auth2.getAuthInstance().signIn();
- }
- function cleanupInbox() {
- gapi.client.gmail.users.messages.list({
- 'userId': 'me',
- 'q': 'is:unread older_than:7d' // Example: Cleanup unread emails older than 7 days
- }).then(function(response) {
- let messages = response.result.messages;
- if (messages && messages.length > 0) {
- for (let i = 0; i < messages.length; i++) {
- let message = messages[i];
- gapi.client.gmail.users.messages.modify({
- 'userId': 'me',
- 'id': message.id,
- 'removeLabelIds': ['UNREAD'] // Example: Remove the 'unread' label
- }).then(function() {
- console.log('Email marked as read:', message.id);
- });
- }
- } else {
- console.log('No messages found.');
- }
- });
- }
Advertisement
Comments
-
- Replace 'YOUR_CLIENT_ID' and 'YOUR_API_KEY' with your actual Google API credentials. This example demonstrates a basic implementation of authorization and inbox cleanup using the Gmail API. It lists unread emails older than 7 days and marks them as read.
- Please note that this code is a simplified example for demonstration purposes. Building a production-ready app would require error handling, better user feedback, and more comprehensive features for inbox management. Also, handling sensitive data like API keys securely is crucial.
Add Comment
Please, Sign In to add comment