I’m a long time google user.
I want to be able to write scripts and connect google apps with with google scripts.
namely, I want a script / tutorial that will show me exactly how to set up a shared label script with detailed instructions.
Google AI studio generated this but it failed miserably. Nothing but errors and NO specific mentions on how to fix it. Google AI Studio doesn’t appear to be aware of Google Workspace.
// Replace these with your OAuth 2.0 credentials
const CLIENT_ID = “aaa”;
const CLIENT_SECRET = “zzz”;
const REFRESH_TOKEN = “YYY”;
// Function to get a new OAuth 2.0 access token
function getOAuthToken() {
const tokenUrl = “https://accounts.google.com/o/oauth2/token”;
const payload = {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
refresh_token: REFRESH_TOKEN,
grant_type: “refresh_token”,
};
const options = {
method: “post”,
contentType: “application/x-www-form-urlencoded”,
payload: payload,
};
const response = UrlFetchApp.fetch(tokenUrl, options);
const tokenData = JSON.parse(response.getContentText());
return tokenData.access_token;
}
function shareEmailsInFolder() {
const labelName = “testtest”; // Label name to monitor
const userBEmail = “userB@example.com”; // Replace with User B’s email
// Get the label by name
const label = GmailApp.getUserLabelByName(labelName);
if (!label) {
Logger.log(Label "${labelName}" not found.
);
return;
}
// Get all threads (emails) with the specified label
const threads = label.getThreads();
// Loop through each thread (email)
threads.forEach(thread => {
const messages = thread.getMessages();
messages.forEach(message => {
// Get the raw email content
const rawContent = message.getRawContent();
// Use the Gmail API to insert the email into User B's account
insertEmailIntoUserBAccount(rawContent, userBEmail, labelName);
});
});
}
function insertEmailIntoUserBAccount(rawContent, userBEmail, labelName) {
const gmailApiUrl = https://gmail.googleapis.com/gmail/v1/users/${userBEmail}/messages/import
;
const payload = {
raw: Utilities.base64EncodeWebSafe(rawContent),
labelIds: [labelName], // Apply the same label in User B’s account
};
const options = {
method: “post”,
contentType: “application/json”,
headers: {
Authorization: Bearer ${getOAuthToken()}
,
},
payload: JSON.stringify(payload),
muteHttpExceptions: true, // To see the full error response
};
try {
const response = UrlFetchApp.fetch(gmailApiUrl, options);
Logger.log(Email inserted into ${userBEmail}'s account: ${response.getContentText()}
);
} catch (error) {
Logger.log(Error inserting email: ${error.toString()}
);
}
}
function setupTrigger() {
// Delete existing triggers to avoid duplicates
const triggers = ScriptApp.getProjectTriggers();
triggers.forEach(trigger => {
ScriptApp.deleteTrigger(trigger);
});
// Create a new trigger to run the script when a new email arrives
ScriptApp.newTrigger(“shareEmailsInFolder”)
.forUser(Session.getActiveUser())
.onNewEmail()
.create();
}