Can I ask you for advice. I have a Google script that does this:
1) check whether there is any conversation marked by an asterisk
2) if so, deselect it, and then forward this conversation to that address
It works well, but I need to easily pimp. Rather than forward, I need to send the message to the address, which would be the subject of a report and found the body of a message by message body was found under the link to the thread found messages and the icing on the cake would have been references to attachments in the message.
function TJ() {
var threads = GmailApp.search('is:starred');
for (var h = 0; h < threads.length; h++) {
var messages = threads[h].getMessages();
for (var i = 0; i < messages.length; i++) {
if (messages[i].isStarred())
{
Logger.log(messages[i].getSubject());
messages[i].unstar();
messages[i].forward("--email-address--", {
cc: "",
bcc: ""
});
}
}
}
}
THX!
This is perfect!
function AddSM2GTDApp() {
var threads = GmailApp.search('is:starred');
for (var h = 0; h < threads.length; h++) {
var messages = threads[h].getMessages();
for (var i = 0; i < messages.length; i++) {
if (messages[i].isStarred())
{
Logger.log(messages[i].getSubject());
var subject = messages[i].getSubject();
Logger.log(messages[i].getBody());
var body = messages[i].getBody();
Logger.log(messages[i].getId());
var id = messages[i].getId();
var label = GmailApp.getUserLabelByName("Add2GTDApp");
threads[h].addLabel(label);
messages[i].unstar();
MailApp.sendEmail({
to: "your#email.com",
subject: subject,
htmlBody: "https://mail.google.com/mail/u/0/#inbox/"+id+"<br>--------------------------------------------------------------------------------------<br>"+body+"<br>--------------------------------------------------------------------------------------<br>Mail to Nirvana Script ",
});
}
}
}
}
Please try the below code , You can add 5 mins time driven event trigger to run the script
function MailForward() {
try{
var glabel = createLabel_("Mail-Forwarded");
var rtm_email = 'abc#abc.com';
var from_email = Session.getActiveUser().getEmail();
var threads = GmailApp.search('in:inbox is:unread newer_than:1d');
var mForward = 0;
for (var i=0;i<threads.length;i++) {
var messages=threads[i].getMessages();
for (var m = 0; m < messages.length; m++){
if (messages[m].isUnread()){
mForward = 0;
var mlabels = threads[i].getLabels();
for (var j = 0; j < mlabels.length; j++) {
Logger.log(mlabels[j].getName());
if (mlabels[j].getName() === "Mail-Forwarded") {
mForward = 1;
}
}
if (mForward===0) {
// Logger.log(messages.length)
// Logger.log(messages[m].getFrom());
var from = messages[m].getFrom();
//Logger.log(messages[m].getDate());
var date = messages[m].getDate();
// Logger.log(messages[m].getSubject());
var subject = messages[m].getSubject();
// Logger.log(messages[m].getTo());
var to = messages[m].getTo();
var body = messages[m].getBody();
var attachment = messages[m].getAttachments();
var emailoptions = ("---------- Forwarded message ----------" +'<br>'+'From: '+from+ "<'" + from.replace(/^.+<([^>]+)>$/, "$1") +"'>"+'<br>'+ 'Date: '+date+'<br>'+ 'Subject: ' +subject+'<br>'+
'To: ' +to+ "<'" + to.replace(/^.+<([^>]+)>$/, "$1") +"'>"+'<br>'+'<br>'+'<br>');
messages[m].forward(rtm_email,{htmlBody: emailoptions + body , Attachment: attachment});
glabel.addToThread(threads[i]);
Logger.log(glabel.getName());
messages[m].markRead();
mForward = 1;
}
}
}
}
} catch(e) {
MailApp.sendEmail("abc#abc.com", "Exception found in Sript", e );
Logger.log(e);
}
}
function autoForwardZoom() {
var s = "";
var m = "";
var c = 0;
var a = "";
var f = "";
var label = 'IT/Zoom';
var subject = 'Disconnected';
var from = 'no-reply#domain.us';
var threads = GmailApp.search("from:" + from + " label:" + label + " is:unread subject:(" + subject + ")", 0, 1);
for (var i = 0; i < threads.length; i++) {
var message = threads[i].getMessages();
c = threads[i].getMessageCount() - 1;
m = threads[i].getMessages()[c];
b = m.getBody();
s = m.getSubject();
a = m.getAttachments();
var returnData = [];
var html = HtmlService.createTemplateFromFile('Temp');
html.data = returnData;
var template = html.evaluate().getContent();
m.forward("youremail#gmail.com", {
replyTo: "myemail#gmail.com",
subject: s,
htmlBody: template + "<br>" + b,
attachments: a
});
GmailApp.markThreadsRead(threads);
}
}
My HTML Template,
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>Dear Team</div>
<div> </div>
<div>Please kindly check zoom controller issue</div>
<div> </div>
<div>Regards</div>
<div><i>please reply this email with word "SOLVED" to earn credits, once you has solved this issue</i></div>
<div> </div>
<div style='text-align: center;'>---------- Forwarded message from Zoom ----------</div>
</body>
</html>
Related
I am once in a while getting this error:
Jan 5, 2023, 11:03:48 AM Error Exception: Failed to retrieve form
data. Please wait and try again. at processForm(Code:2:22)
Line 2 is:
var form = FormApp.getActiveForm();
Full script
function processForm(event) {
var form = FormApp.getActiveForm();
Logger.log("Form retrieved " + form)
var allResponses = form.getResponses();
var latestResponse = allResponses[allResponses.length - 1];
var itemResponses = latestResponse.getItemResponses();
//const itemResponses = event.response.getItemResponses();
const propertyAddress = itemResponses[0].getResponse();
Logger.log("Processing address " + propertyAddress);
// Get the number of units. index 5
const moreThan200Units = parseInt(itemResponses[5].getResponse(), 10);
var mainFolder = null;
if(moreThan200Units > 199) {
mainFolder = DriveApp.getFolderById('xx');
} else {
mainFolder = DriveApp.getFolderById('yy');
}
var propertyFolder = null;
for (var i = 0; i < itemResponses.length; i++) {
Logger.log(itemResponses[i].getItem().getType())
if (itemResponses[i].getItem().getType() == "FILE_UPLOAD") {
if(propertyFolder == null) {
propertyFolder = mainFolder.createFolder(propertyAddress);
}
var ids = itemResponses[i].getResponse();
for (var j = 0; j < ids.length; j++) {
var uploadedFile = DriveApp.getFileById(ids[j]);
Logger.log("Moving file" + uploadedFile + " to " + propertyFolder);
uploadedFile.moveTo(propertyFolder);
}
}
}
}
This script import opportunities that we get. It populates rows which then calculates some numbers such as interest and stuff. However, I now have errors when populating my cells (#REF error, see pictures below). Nothing has changed so my first guess is it has do with the processing of the sheet which has become too heavy.
`
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createAddonMenu();
menu.addItem('Créer étude', 'init');
menu.addToUi();
}
function init() {
ss = SpreadsheetApp.getActiveSpreadsheet();
identifyJe();
sheetMaker = ss.getActiveSheet();
currentRow = ss.getActiveCell().getRowIndex();
ssEtudes = SpreadsheetApp.openById(getSheetEtudesId());
var ui = SpreadsheetApp.getUi();
var respon se = ui.alert(
'Ligne sélectionnée : ' + currentRow + '. Exécuter ?',
ui.ButtonSet.OK_CANCEL
);
if (response !== ui.Button.OK) return;
doEtude();
doContrat();
doPhases();
}
function doEtude(nomEtude) {
var etudeData = [];
for (var i = 0; i < etudeNamedRanges.length; i++) {
var column = ss.getRangeByName(etudeNamedRanges[i]).getColumn();
etudeData.push(sheetMaker.getRange(currentRow, column).getValue());
}
var destSheet = ssEtudes.getSheetByName('etudes');
var rowToAppend = getFirstEmptyRow(destSheet, 0);
for (var i = 0; i < etudeData.length; i++) {
var column = ssEtudes.getRangeByName(etudeNamedRanges[i]).getColumn();
destSheet.getRange(rowToAppend, column).setValue(etudeData[i]);
}
}
function doContrat() {
var contratData = [];
for (var i = 0; i < contratNamedRanges.length; i++) {
var column = ss.getRangeByName(contratNamedRanges[i]).getColumn();
contratData.push(sheetMaker.getRange(currentRow, column).getValue());
}
var destSheet = ssEtudes.getSheetByName('contrats');
var rowToAppend = getFirstEmptyRow(destSheet, 11);
for (var i = 0; i < contratData.length; i++) {
destSheet.getRange(rowToAppend, i + 4).setValue(contratData[i]);
}
}
function doPhases() {
var phasesCoords = getPhasesCoords();
var phasesData = [];
for (var i = 0; i < phasesCoords.length; i++) {
var phaseData = getPhaseData(phasesCoords[i]);
phaseData.unshift(i + 1);
phasesData.push(phaseData);
}
var destSheet = ssEtudes.getSheetByName('phases');
var rowToAppend = getFirstEmptyRow(destSheet, 9);
var columns = [];
for (var nPhase = 0; nPhase < phasesData.length; nPhase++) {
var phaseData = phasesData[nPhase];
for (var i = 0; i < phaseData.length; i++) {
if (columns[i] === undefined)
columns[i] = ssEtudes.getRangeByName(phasesNamedRanges[i]).getColumn();
destSheet
.getRange(rowToAppend + nPhase, columns[i])
.setValue(phaseData[i]);
}
}
}
`
Type of formula
The results
The error, which translates into The result could not be auto-expanded. Please insert new columns (1).
The results actually appear for some time and disappear after a few seconds, constantly. Does it have something to do with the size of the spreadsheet ?
I'm trying to create a script that will allow me to search for e-mails and their attachments by label name or no user labels. If in searchForLabels is more than one entry, the script does not work.
function searchLabels(){
//if there is more than one entry here, the script does not work
var searchForLabels =
[
'has:nouserlabels',
'label:Test1'
];
for (var l = 0; l < searchForLabels.length; l++) {
var threads = GmailApp.search('in:inbox newer_than:4d' + searchForLabels);
var msgs = GmailApp.getMessagesForThreads(threads);
Logger.log(searchForLabels)
if (searchForLabels == 'has:nouserlabels'){
for (var i = 0 ; i < msgs.length; i++) {
for (var j = 0; j < msgs[i].length; j++) {
var message = msgs[i][j];
var from = message.getFrom();
var subject = message.getSubject();
var getAttachments = message.getAttachments();
var body = message.getPlainBody();
var getTo = message.getTo();
Logger.log(subject)
for (var k = 0; k < getAttachments.length; k++) {
var attachment = getAttachments[k];
var content = attachment.getContentType();
//rest of my code
}
}
}
}
}
}
I made two little changes over your code. After testing it, it works as you requested.
The first one is on the var threads = GmailApp.search('in:inbox newer_than:4d ' + searchForLabels[l]); line. I used the l iterator on the searchForLabels array. I used it because, reading the context of the line, it seems appropriate. This change will iterate over the tags. Forgive me if this was not your original intention.
The second change is required for the script to work. I commented out the if (searchForLabels == 'has:nouserlabels') {, because it will never be true if the searchForLabels array has more than one element. This is the error that you detected. Please, notice how the correspondent } is commented out too.
This is the final and working version of the script:
function searchLabels() {
//if there is more than one entry here, the script does not work
var searchForLabels = [
'has:nouserlabels',
'label:Test1'
];
for (var l = 0; l < searchForLabels.length; l++) {
var threads = GmailApp.search('in:inbox newer_than:4d ' + searchForLabels[l]);
var msgs = GmailApp.getMessagesForThreads(threads);
Logger.log(searchForLabels)
//if (searchForLabels == 'has:nouserlabels') {
for (var i = 0; i < msgs.length; i++) {
for (var j = 0; j < msgs[i].length; j++) {
var message = msgs[i][j];
var from = message.getFrom();
var subject = message.getSubject();
var getAttachments = message.getAttachments();
var body = message.getPlainBody();
var getTo = message.getTo();
Logger.log(subject)
for (var k = 0; k < getAttachments.length; k++) {
var attachment = getAttachments[k];
var content = attachment.getContentType();
//rest of my code
}
}
}
//}
}
}
I want to add that you can use the Gmail API on Apps Script to accomplish your request in a simple way. In particular, you can use Users.messages LIST to list all the mails with your selected tags. There you can see an example (click over JavaScript) where a function is ready to make a search. To enable this API you shall follow the guide for activating advanced services. Do not hesitate to ask for more clarifications or any question.
function searchLabels() {
var searchForLabels = [
'has:nouserlabels',
'label:Test1'
];
for (var l = 0; l < searchForLabels.length; l++) {
var threads = GmailApp.search('in:inbox newer_than:4d ' + searchForLabels[l]);
var msgs = GmailApp.getMessagesForThreads(threads);
Logger.log(searchForLabels)
if (searchForLabels[l] == 'has:nouserlabels') { //limits emails to those without tag
//if (searchForLabels[l] == 'label:Test1') { //or to those with tag
for (var i = 0; i < msgs.length; i++) {
for (var j = 0; j < msgs[i].length; j++) {
var message = msgs[i][j];
var from = message.getFrom();
var subject = message.getSubject();
var getAttachments = message.getAttachments();
var body = message.getPlainBody();
var getTo = message.getTo();
Logger.log(subject)
for (var k = 0; k < getAttachments.length; k++) {
var attachment = getAttachments[k];
var content = attachment.getContentType();
//rest of my code
}
}
}
}
}
}
I am creating a script that sends a custom email right after you send the form. It works perfectly but I wanted it to work also when I edit the form it sends a automatic email with the changes made.
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers)
ScriptApp.deleteTrigger(triggers[i]);
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit().create();
}
function SendGoogleForm(e) {
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "Please paste this!\n\n";
var subject = "Email: ID: ";
var email = "";
//
var form = FormApp.openById('*******************'); //this is the ID in the url of your live form
var formResponses = form.getResponses();
//
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
}
for(var i in headers) {
if ( e.namedValues[headers[i]].toString() != "") {
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n";
}
}
subject += e.namedValues[headers[2]].toString();
email += e.namedValues[headers[1]].toString();
message += "Edit Link: " + formResponse.getEditResponseUrl();
MailApp.sendEmail(email, subject, message);
}
I've found a script that may help to send a email when it is edited but I am not sure how I can implement it(found it in google docs forums https://productforums.google.com/forum/#!topic/docs/-guIl5QlvKk):
function checkResponse() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Form Responses 1');
var lastRow = s.getLastRow();
var range = s.getRange('A' + lastRow + ':C' + lastRow);
var notes = range.getNotes();
var values = range.getValues();
var changedFlag = null;
var body = '';
for (var i = 0; i < notes[0].length; i++ ) {
if ( notes[0][i] == 'Responder updated this value.' ) {
changedFlag = true;
// We know only to send the changed values
// Add changed value to email msg
body += values[0][i];
// May also want to clear the note as it remains after future edits of other values as well
s.getRange(lastRow, i).clearNote();
}
}
if ( !changedFlag ) {
// Email the whole row of values
for (var i = 0; i < values.length; i++) {
body += values[0][i];
}
}
GmailApp.sendEmail(recipient, subject, body)
}
I would like to scan all my emails in Gmail, and extract only the mailer-daemon messages (to identify rejected email addresses).
When I'm using these methods, None of the mailer-daemon messages are returned - only the "valid" messages:
var ss = SpreadsheetApp.openById("1e29xgV1UU63SJEwF2aWQpWpcXMxyiylwEMGbuvbwADw");
var sheet = ss.getSheetByName("Email Addresses");
var row = 1;
sheet.getRange(row,1).setValue("Email Addresses");
row++;
var threads = GmailApp.getInboxThreads();
for (var i = 0; i < threads.length; i++) {
var messages = GmailApp.getMessagesForThread(threads[i]);
for (var j = 0 ; j < messages.length; j++) {
var txtBody = messages[i].getPlainBody();
var txtSender = messages[i].getFrom();
sheet.getRange(row,1).setValue(txtBody);
sheet.getRange(row,2).setValue(txtSender);
row++;
}
}
What can I use to process the mailer-daemon messages from the Mail Delivery Subsystem?
Thanks!
You should match the FROM: field of the message, something like:
var txtSender = messages[i].getFrom();
if (txtSender.indexOf("mailer-daemon") !== -1) {
// Log the entry in the spreadsheet
}
You should be filtering threads from the query itself, its more optimal (also paged).
function getBounced() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Bounced Addresses");
var row = 1;
var regExp = /[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}/i // "i" is for case insensitive
var threads = GmailApp.search('from:"mailer-daemon" subject:(failure|undeliverable)', 0, 50);
for (var i = 0; i < threads.length; i++) {
var messages = GmailApp.getMessagesForThread(threads[i]);
for (var j = 0 ; j < messages.length; j++) {
var txtSubject = messages[j].getSubject();
var txtBody = messages[j].getBody();
var bouncedEmail = regExp.exec(txtBody)[0];
sheet.getRange(row,1).setValue(bouncedEmail);
sheet.getRange(row,2).setValue(txtSubject);
row++;
}
}
}
I also added a little code to extract the bounced/rejected email with a RegExp