Change sendAs email address in google mail api - google-apps-script

I have searched but cannot find any examples
What I am sending is
//Send Email
var emailContents =
{
to: techManagerEmail+","+organiserEmail,
subject: "New Technical Support Request for " + eventName,
body: "Event Name: "+eventName+ "\n\n"+"Event Room: "+eventRoom+ "\n\n"+eventDescription +"\n\n"+ allEvents + "\n\n" + "Google Folder: "+newFolderLink+"\n \n"+techTeam+" Calendar Link: "+ calendarLink + "\n\n" + "Date Submitted: " + submitionDate + " by: " + submitterEmail,
};
MailApp.sendEmail(emailContents);
}
When I send, it sends as the user that created the form (me) when I want the person filling the form to be the sender - (I would also like the person filling the form to be the creator of the calendar event, but I think that may be a larger issue). It would also be nice to be able to change the display name.
I have looked at the api sendAs options but am struggling to work out how to use it or the syntax.
Any advice would be appreciated.
As requested, full code:
function onSubmit(e)
{
//Set General Variables
var formResponses = e.response.getItemResponses();
var submitterEmail = e.response.getRespondentEmail();
var submitionDate = e.response.getTimestamp();
var eventName = formResponses[0].getResponse();
var eventDescription = formResponses[1].getResponse();
var moduleCode = formResponses[2].getResponse();
var noStudents = formResponses[3].getResponse();
var organiser = formResponses[4].getResponse();
var organiserEmail = formResponses[5].getResponse();
var eventRoom = formResponses[6].getResponse();
var techTeam = formResponses[7].getResponse();
var supportRequired = formResponses[8].getResponse();
var supportDescription = formResponses[9].getResponse();
var equipmentRequired = formResponses[10].getResponse();
var startDate = formResponses[11].getResponse();
var nextAction = formResponses[18].getResponse();
var supportDateNo = 11;
var supportStartNo = 12;
var eventStartNo = 13;
var eventEndNo = 14;
var supportEndNo = 15;
var eventDaysDataNo = 16;
var eventEndDateNo = 17;
var nextActionNo = 18;
var nextActionSwitch = 1;
var loopNo = 1;
var calendarId = CalendarApp.getCalendarById(calId);
var allEvents ="";
var day = 1000*60*60*24
var eventDescription = 'Organiser: ' + organiser + '\n \n' +
'Module Code: ' + moduleCode + '\n \n' +
'Description of the Event: ' + eventDescription + '\n \n' +
'Type of support: ' + supportRequired + '\n \n' +
'Description of Support: ' + supportDescription + '\n \n'+
'Number of Students: ' + noStudents + '\n \n'+
'Equipment Required: ' + equipmentRequired + '\n\n';
//General Operations
if(organiserEmail==""){var organiserEmail = submitterEmail};
if(techTeam=="Performance Studios")
{
var calId = "****";
var techManagerEmail = "****";
var calendarLink = "****";
var parentFolder = DriveApp.getFolderById('****');
};
if(techTeam=="****")
{
var calId = "****";
var techManagerEmail = "****";
var calendarLink = "****";
var parentFolder = DriveApp.getFolderById('****');
};
if(techTeam=="****")
{
var calId = "****";
var techManagerEmail = "****";
var calendarLink = "****";
var parentFolder = DriveApp.getFolderById('****');
};
if(techTeam=="****")
{
var calId = "****";
var techManagerEmail = "****";
var calendarLink = "****";
var parentFolder = DriveApp.getFolderById('****');
};
//create attachments
var folderName = startDate + ' ' + eventName
var newFolder = parentFolder.createFolder(folderName).getId();
var newFolderLink = DriveApp.getFolderById(newFolder).getUrl();
//Calendar Creation Loop
while(nextActionSwitch==1)
{
//Set Variables
var supportDate = formResponses[supportDateNo].getResponse();
var supportStart = formResponses[supportStartNo].getResponse();
var eventStart = formResponses[eventStartNo].getResponse();
var eventEnd = formResponses[eventEndNo].getResponse();
var supportEnd = formResponses[supportEndNo].getResponse();
var eventDaysData = formResponses[eventDaysDataNo].getResponse();
var eventEndDate = formResponses[eventEndDateNo].getResponse();
var nextAction = formResponses[nextActionNo].getResponse();
var indivudualTechDetails = "";
var individualEventDetails = "";
var individualRepeatDetails = "";
//Time Operations
var eventEndDate = eventEndDate.replace(/-/g, "");
if (eventDaysData == "All"){var eventDaysData = "MO,TU,WE,TH,FR,SA,SU,"};
if (eventDaysData =="No Repeat"){var eventDaysData = ""; var eventEndDate = ""};
if (eventEndDate == ""){var eventDaysData = ""};
var alteredEndDate = Number(eventEndDate)+1;
var startDateTime = new Date(supportDate+"T"+supportStart+":00");
var endDateTime = new Date(supportDate+"T"+supportEnd+":00.000Z");
if (endDateTime<=startDateTime){var endDateTime = new Date(endDateTime.getTime() + day)};
var start = Utilities.formatDate(startDateTime, "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
var end = Utilities.formatDate(endDateTime, "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
var finalDescription = eventDescription;
if (eventStart!=""){var finalDescription = eventName + ' Start Time: ' + eventStart +'\n' + eventName + ' End Time: ' + eventEnd + '\n \n' + eventDescription};
//Date Display Operations
var eventDay = startDateTime.getDate();
var eventMonth = startDateTime.getMonth()+1;
var eventYear = startDateTime.getFullYear();
var eventEmailDate = eventDay+"/"+eventMonth+"/"+eventYear;
var repeatEndDate = new Date(eventEndDate+"T"+supportStart+":000Z");
var eventEndDay = repeatEndDate.getDate();
var eventEndMonth = repeatEndDate.getMonth()+1;
var eventEndYear = repeatEndDate.getFullYear();
var eventEmailEndDate = eventEndDay+"/"+eventEndMonth+"/"+eventEndYear;
//Create Event
var event =
{
summary: eventName,
location: eventRoom,
start: {dateTime: start, timeZone: "GMT"},
end: {dateTime: end, timeZone: "GMT"},
description: finalDescription,
colorId: 8,
attendees: [{email: submitterEmail}, {email:organiserEmail}],
attachments: [{fileId: newFolder, fileUrl:newFolderLink, title: eventName+" Folder"}],
"recurrence": ["RRULE:FREQ=DAILY;UNTIL="+alteredEndDate+";BYDAY="+eventDaysData]
};
if (eventEndDate == ""|| eventDaysData == "No Repeat")
{
var event =
{
summary: eventName,
location: eventRoom,
start: {dateTime: start, timeZone: "GMT"},
end: {dateTime: end, timeZone: "GMT"},
description: finalDescription,
colorId: 8,
attendees: [{email: submitterEmail}, {email:organiserEmail}],
attachments: [{fileId: newFolder, fileUrl:newFolderLink, title: eventName+" Folder"}],
};
};
var eventLink = Calendar.Events.insert(event, calId, {SendNotifications: true, supportsAttachments:true}).getHtmlLink();
//Event Details
var individualTechDetails =
"Instance: " + loopNo + "\n\n" +
"Start Date: " + eventEmailDate + "\n\n" +
"Tech Start Time: " + supportStart + "\n\n" +
"Tech End Time: " + supportEnd + "\n\n";
if (eventStart != ""){var individualEventDetails =
"Event Start Time: " + eventStart + "\n\n" +
"Event End Time: " + eventEnd + "\n\n"};
if (eventEndDate != ""){ var individualRepeatDetails =
"Repeats: " + eventDaysData + "\n\n"+
"End Date: " + eventEndDate+"\n\n"};
var combinedEventDetails = individualTechDetails + individualEventDetails + individualRepeatDetails + "Event Link: "+ eventLink;
var allEvents = allEvents + combinedEventDetails + "\n\n -- \n \n";
//Set Loop Values
var nextActionSwitch = 0;
if (nextAction=="Add dates with a different pattern")
{
var nextActionSwitch = 1;
var loopNo = loopNo +1;
var supportDateNo = supportDateNo +8;
var supportStartNo = supportStartNo +8;
var eventStartNo = eventStartNo +8;
var eventEndNo = eventEndNo +8;
var supportEndNo = supportEndNo +8;
var eventDaysDataNo = eventDaysDataNo +8;
var eventEndDateNo = eventEndDateNo +8;
var nextActionNo = nextActionNo +8;
};
};
//Send Email
var requestorEmails = submitterEmail + ", " + organiserEmail;
if (organiserEmail == submitterEmail){requestorEmails = organiserEmail};
var emailContents =
{
to: techManagerEmail+","+requestorEmails,
subject: "New Technical Support Request for " + eventName,
body: "Event Name: "+eventName+ "\n\n"+"Event Room: "+eventRoom+ "\n\n"+eventDescription +"\n\n"+ allEvents + "\n\n" + "Google Folder: "+newFolderLink+"\n \n"+techTeam+" Calendar Link: "+ calendarLink + "\n\n" + "To create another event: ****" + "\n\n" + "Date Submitted: " + submitionDate + " by: " + submitterEmail,
name: techTeam + " Technical Support Requests",
};
MailApp.sendEmail(emailContents);
}

There are limited ways you can achieve this. The only way to achieve that is by logging with the account of the person filling the form. If you're running the script automatically via a trigger, just set the trigger with this account.
There's an open issue about this on Apps Script tracker:
Issue Tracker
Hope this answers your question!!

Related

Script do nothing

I'm trying to write code to save data and read data from telegram to google sheets using this code
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doPost(e) {
var data = JSON.parse(e.postData.contents);
var id = data.message.chat.id;
var username = data.message.chat.username;
var date = Utilities.formatDate(new Date(), "GMT+9", "dd/MM/yyyy");
var hour = Utilities.formatDate(new Date(), "GMT+9", "HH:mm:ss");
var text = data.message.text;
if (text.startsWith("/start")) {
sendText(id,"Hello " + username + ", welcome to my bot");
} else if (text.startsWith("/input")) {
const text = String(data.message.text).replace("/input ", "");
var item = text.split(",");
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheet1);
sheet.appendRow([date,hour,id,username,item[1],item[2],item[3],item[4],item[5],item[6],item[7],item[8],item[9]]);
sendText(id,"data has been saved");
} else if (text.startsWith("/search")) {
const text = String(data.message.text).replace("/search ", "");
var keyword = text.split(" ");
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheet2);
var data = sheet.getRange("A2:E").getValues();
var found = false;
for (var i = 0; i < data.length; i++) {
if (data[i][0] == keyword[1]) {
sendText(id, "Data found!\n" + "data1 = " + data[i][0] + "\n" + "data2 = " + data[i][1] + "\n" + "data3 = " + data[i][2] + "\n" + "data4 = " + data[i][3] + "\n" + "data5 = " + data[i][4]);
found = true;
}
}
if (!found) {
sendText(id,"data not found");
}
} else if (text.startsWith("/help")) {
sendText(id,"/input (date, hour, id, username, item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7])\n/search (keyword)");
}
}
I have tried to use openAi chat to help fix my code, but still not work.

Referencing Edited Row Instead of getLastRow

My current code is listed below (triggered by on change). It creates a calendar event when a new "lead" is entered in our lead sheet via AppSheet. It currently only runs when a new lead aka new row is added. I would like it to also run when the appointment date is added or modified, so if a lead is entered but appointment is not set up at that time, it can be entered later and the calendar event will be created. Therefore, I know that if (e.changeType == "OTHER") will need to be changed to if (e.changeType == "OTHER" || "EDIT") and that I can no longer use sheet.getLastRow().
My question is what should I replace sheet.getLastRow() with and most importantly, how will I call/reference the row that was impacted by:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("Y:Y");
if (e.changeType == "OTHER" || "EDIT")
Essentially, what do I need to set the current var lastRow equal to so that it will call the row where the change was made instead of the last row? (I will of course change the name of the variable from lastRow to something more applicable when I do so)
Original Code:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
// Calendar to output requests
var calendar = CalendarApp.getCalendarById('youremail#gmail.com');
// Creates an object from the last form submission
function getSubmission() {
this.timestamp = sheet.getRange(lastRow, 9).getValue();
this.accountNumber = sheet.getRange(lastRow, 10).getValue();
this.contactLastName = sheet.getRange(lastRow, 11).getValue();
this.contactFirstName = sheet.getRange(lastRow, 12).getValue();
this.contactPhoneNumber = sheet.getRange(lastRow, 15).getValue();
this.contactEmail = sheet.getRange(lastRow, 16).getValue();
this.userLastName = sheet.getRange(lastRow, 37).getValue();
this.userFirstName = sheet.getRange(lastRow, 38).getValue();
this.userPhoneNumber = sheet.getRange(lastRow, 39).getValue();
this.userEmail = sheet.getRange(lastRow, 40).getValue();
this.streetAddress = sheet.getRange(lastRow, 17).getValue();
this.city = sheet.getRange(lastRow, 18).getValue();
this.state = sheet.getRange(lastRow, 19).getValue();
this.zipCode = sheet.getRange(lastRow, 20).getValue();
this.type = sheet.getRange(lastRow, 21).getValue();
this.equipment = sheet.getRange(lastRow, 22).getValue();
this.typeOfLead = sheet.getRange(lastRow, 13).getValue();
this.sourceOfLead = sheet.getRange(lastRow, 14).getValue();
this.notes = sheet.getRange(lastRow, 23).getValue();
this.date = new Date(sheet.getRange(lastRow, 24).getValue());
this.appointmentStart = sheet.getRange(lastRow, 25).getValue();
this.appointmentEnd = sheet.getRange(lastRow, 26).getValue();
this.direction = sheet.getRange(lastRow, 27).getValue();
this.callOnWay = sheet.getRange(lastRow, 28).getValue();
return this;
}
// Creates a calendar event using the submitted data
function updateCalendar(request) {
request.date.setHours(request.appointmentStart.getHours());
request.date.setMinutes(request.appointmentStart.getMinutes());
var endTime = new Date(request.date);
endTime.setHours(request.appointmentEnd.getHours());
endTime.setMinutes(request.appointmentEnd.getMinutes())
var event = calendar.createEvent(
request.state + " " + request.direction + " EST " + request.contactLastName + ", " + request.contactFirstName + " " + request.callOnWay,
request.date,
endTime
)
.setLocation(request.streetAddress + " " + request.city + ", " + request.state + " " + request.zipCode
)
.setDescription("Account # " + request.accountNumber + "\n" + "\n" + request.contactFirstName + " " + request.contactLastName + "\n" + request.contactPhoneNumber + "\n" + request.contactEmail + "\n" + "\n" + "Notes: " + request.type + " - " + request.equipment + ". " + request.notes + ".\n" + "Lead: " + request.typeOfLead + " - " + request.sourceOfLead + "." + "\n" + "\n" + "Jim: Scanned:____ " + "Inv. Adj:____ " + "QB:____ " + "Est. SL:____" + "\n" + "\n" + "Tracy: QB:____" + " Scan:____" + " Letter:____" + " Lead Sheet:____" + " Ref. Check #:____"
)
}
// --------------Main--------------
function main() {
var request = getSubmission();
updateCalendar(request);
}
function runMain(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("Y:Y");
if (e.changeType == "OTHER") {
main();
}
}
I am still quite new to writing in App Script, so any help is greatly appreciated!
Updated code with suggestions from #YuriKhristich:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
// Calendar to output requests to
var calendar = CalendarApp.getCalendarById('youremail#gmail.com');
// Creates an object from the last submission
function getSubmission(row) {
var data = sheet.getRange(row,9,1,40).getValues();
this.timestamp = row[ 9];
this.accountNumber = row[10];
this.contactLastName = row[11];
this.contactFirstName = row[12];
this.contactPhoneNumber = row[15];
this.contactEmail = row[16];
this.userLastName = row[37];
this.userFirstName = row[38];
this.userPhoneNumber = row[39];
this.userEmail = row[40];
this.streetAddress = row[17];
this.city = row[18];
this.state = row[19];
this.zipCode = row[20];
this.type = row[21];
this.equipment = row[22];
this.typeOfLead = row[13];
this.sourceOfLead = row[14];
this.notes = row[23];
this.date = new Date(row[24]);
this.appointmentStart = row[25];
this.appointmentEnd = row[26];
this.direction = row[27];
this.callOnWay = row[28];
return this;
}
// Creates a calendar event using the submitted data
function updateCalendar(request) {
request.date.setHours(request.appointmentStart.getHours());
request.date.setMinutes(request.appointmentStart.getMinutes());
var endTime = new Date(request.date);
endTime.setHours(request.appointmentEnd.getHours());
endTime.setMinutes(request.appointmentEnd.getMinutes())
var event = calendar.createEvent(
request.state + " " + request.direction + " EST " + request.contactLastName + ", " + request.contactFirstName + " " + request.callOnWay,
request.date,
endTime
)
.setLocation(request.streetAddress + " " + request.city + ", " + request.state + " " + request.zipCode
)
.setDescription("Account # " + request.accountNumber + "\n" + "\n" + request.contactFirstName + " " + request.contactLastName + "\n" + request.contactPhoneNumber + "\n" + request.contactEmail + "\n" + "\n" + "Notes: " + request.type + " - " + request.equipment + ". " + request.notes + ".\n" + "Lead: " + request.typeOfLead + " - " + request.sourceOfLead + "." + "\n" + "\n" + "Jim: Scanned:____ " + "Inv. Adj:____ " + "QB:____ " + "Est. SL:____" + "\n" + "\n" + "Tracy: QB:____" + " Scan:____" + " Letter:____" + " Lead Sheet:____" + " Ref. Check #:____"
)
}
// --------------Main--------------
function main() {
var request = getSubmission(lastRow);
updateCalendar(request);
}
function runMain(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("Y:Y");
if (e.changeType == "OTHER") {
main();
}
}
function onEdit(e) {
if (e.range.columnStart != 25) return;
var request = getSubmission(e.range.rowStart);
updateCalendar(request);
}
Receiving the error message "TypeError: Cannot read property 'getHours' of undefined" when adding a new lead or editing appointment date.
runMain is being triggered via the installable trigger On Change.
Will an On Edit trigger need to be implemented to run the onEdit function or is that repetitive?
You can create another installable trigger onEdit (either manually or in Apps Script) to check which row was edited and then call getSubmission with that row number as parameter.
function getRow(e) {
var currentRow = e.range.getRow();
var request = getSubmission(currentRow);
updateCalendar(request);
}
Try to change the functions getSubmission() this way:
function getSubmission(row) { // <-- add 'row' argument here
var data = sheet.getRange(row,9,1,40).getValues(); // make one call to server instead of 24
this.timestamp = row[ 9];
this.accountNumber = row[10];
this.contactLastName = row[11];
this.contactFirstName = row[12];
this.contactPhoneNumber = row[15];
this.contactEmail = row[16];
this.userLastName = row[37];
this.userFirstName = row[38];
this.userPhoneNumber = row[39];
this.userEmail = row[40];
this.streetAddress = row[17];
this.city = row[18];
this.state = row[19];
this.zipCode = row[20];
this.type = row[21];
this.equipment = row[22];
this.typeOfLead = row[13];
this.sourceOfLead = row[14];
this.notes = row[23];
this.date = new Date(row[24]);
this.appointmentStart = row[25];
this.appointmentEnd = row[26];
this.direction = row[27];
this.callOnWay = row[28];
return this;
}
Change the main() function this way:
function main() {
var request = getSubmission(lastRow); // <-- add 'lastRow' argument here
updateCalendar(request);
}
And add the onEdit() function:
function onEdit(e) {
if (e.range.columnStart != 25) return; // if column Y
// probably it makes sense to check the name of the sheet as well
var request = getSubmission(e.range.rowStart);
updateCalendar(request);
}

Im trying to run 2 Functions in one time but there seems to be something wrong

I have 2 main Functions that I want to run in one go which is test_FolderMaker();, and copyfile(); but the problem is that an error says "no folder" and test_FolderMaker(); does not create a folder at first run and copyfile(); will not run without the folder created by the first main function but at second run it does run and the function works.
This is what I have at the moment:
function new_Patient_Record(){
var folder_Maker = test_FolderMaker();
if (folder_Maker = true){
(copyfile()
);}
}
function test_FolderMaker()
{
var t = new Date();
var ids = false;
var res = createFoldersTasks_(ids);
Logger.log(res);
Logger.log('Time to run the script = ' + (new Date() -t) + ' ms.');
}
function copyfile() {
var ss = SpreadsheetApp.getActive();
var activeSheet = ss.getSheetByName("sheet_Patients");
var activeSheetFM = ss.getSheetByName("_FolderMaker_");
var lastRow = activeSheet.getLastRow();
var data = activeSheet.getRange(lastRow,2,1,1).getValue();
var secondData = activeSheet.getRange(lastRow,3,1,1).getValue();
var folder_Name = [data+ ", " +secondData];
var folders = DriveApp.getFoldersByName(folder_Name);
var dest_folder;
if (folders.hasNext()) {
dest_folder = folders.next();
} else {
throw new Error("No folder.")
}
activeSheetFM.getRange(2,4,1,1).setValue(dest_folder.getId());
var Checkup_Form = DriveApp.getFileById("106-03HR1uYZPIYX-9bOFxpcpLjo-qolnus13Dqtyr2k");
var VDH_Form = DriveApp.getFileById("1ZwSvFIzIppGVw29XPAs5o7cgnrbvS3uE8e-nz2fFrDk");
var excel_File = DriveApp.getFileById("1Xidcg8jPA9fFJeH02NlXvMhBmkIQi-9-");
var final_Excel_File = excel_File.makeCopy(data+ ', '+ secondData + ' ' + Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd') + ' ' + excel_File.getName());
final_Excel_File.moveTo(dest_folder);
var final_VDH_Form = VDH_Form.makeCopy(data+ ', '+ secondData + ' ' + Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd') + ' ' + VDH_Form.getName());
final_VDH_Form.moveTo(dest_folder);
var final_Checkup_Form = Checkup_Form.makeCopy(data+ ', '+ secondData + ' ' + Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd') + ' ' + Checkup_Form.getName());
final_Checkup_Form.moveTo(dest_folder);
}
When I separate both of them running it actually works so im thinking that there's something wrong with the new_Patient_Record() function. Thanks
function createFoldersTasks_(ids)
{
var t = new Date();
getSettings_();
var d1 = CCC_.STR_DELIMEER1;
var d2 = CCC_.STR_DELIMEER2;
var allids = CCC_.STR_IDS_FOLDERMAKER.split(d2);
var allFolderIds = CCC_.STR_FOLDERIDS_FOLDERMAKER.split(d2);
var allFolderPaths = CCC_.STR_PATHS_FOLDERMAKER.split(d2);
if (ids) { var taskIds = ids.split(d1); }
else { var taskIds = allids; }
// loop tasks
var folderMaker = {}, index;
var delim = CCC_.STR_PATHDELIM_FOLDERMAKER;
for (var i = 0; i < taskIds.length; i++)
{
index = allids.indexOf(taskIds[i]);
folderMaker.names = allFolderPaths[index].split(delim);
folderMaker.folderId = allFolderIds[index];
createFolderByTask_(folderMaker);
}
return 0;
}

Google app script triggering twice after Google form submit

I'm having issue with my script running twice in a Google Form and the linked Sheets. I have one form submit trigger. If I delete this trigger, the script doesn't run at all on a form submit. If I add the trigger back in, it will trigger twice -- but there is only one form submittal in the sheet responses. I thought that maybe I was clicking the form submittal twice, but that doesn't seem to be it. Thanks.
Here is the code:
function myFunction(e) {
// Set values for event "e" from Response form, each number being a column in the spreadsheet. Column zero is not used - it is the timestamp
var JobNumber = e.values[1];
// Create an array from the PNEZD field in the form then find the array location for the inputted shot number
var PNEZD_field = e.values[2];
var PNEZD_array = Utilities.parseCsv(PNEZD_field);
var StructureNumber = e.values[3];
for (i = 0; i < PNEZD_array.length; i++) {
if (PNEZD_array[i][0] == StructureNumber) {
var Elevation = PNEZD_array[i][3];
var Easting = PNEZD_array[i][2];
var Northing = PNEZD_array[i][1];
}
}
// STRUCTURE TYPE AND SIZE
var StructureType = e.values[4];
var StructureSize = e.values[5];
// PIPE NUMBER 1
var PipeSize1 = e.values[6];
var PipeMaterial1 = e.values[7];
var PipeDirection1 = e.values[8];
var PipeMeasureDown1 = e.values[9];
// PIPE NUMBER 2
var PipeSize2 = e.values[10];
var PipeMaterial2 = e.values[11];
var PipeDirection2 = e.values[12];
var PipeMeasureDown2 = e.values[13];
// PIPE NUMBER 3
var PipeSize3 = e.values[14];
var PipeMaterial3 = e.values[15];
var PipeDirection3 = e.values[16];
var PipeMeasureDown3 = e.values[17];
// PIPE NUMBER 4
var PipeSize4 = e.values[18];
var PipeMaterial4 = e.values[19];
var PipeDirection4 = e.values[20];
var PipeMeasureDown4 = e.values[21];
// PIPE NUMBER 5
var PipeSize5 = e.values[22];
var PipeMaterial5 = e.values[23];
var PipeDirection5 = e.values[24];
var PipeMeasureDown5 = e.values[25];
// Calculate Invert Elevations:
var Dip1 = Elevation - PipeMeasureDown1;
var Dip2 = Elevation - PipeMeasureDown2;
var Dip3 = Elevation - PipeMeasureDown3;
var Dip4 = Elevation - PipeMeasureDown4;
var Dip5 = Elevation - PipeMeasureDown5;
// Build structure information
var firstLine = StructureType + " " + StructureSize + "\n";
var secondLine = "Rim=" + Elevation + "\n";
var thirdLine = PipeSize1 + " " + PipeMaterial1 + " I.E. " + PipeDirection1 + "=" + Dip1 + "'\n";
var fourthLine = PipeSize2 + " " + PipeMaterial2 + " I.E. " + PipeDirection2 + "=" + Dip2 + "'\n";
var fifthLine = PipeSize3 + " " + PipeMaterial3 + " I.E. " + PipeDirection3 + "=" + Dip3 + "'\n";
var sixthLine = PipeSize4 + " " + PipeMaterial4 + " I.E. " + PipeDirection4 + "=" + Dip4 + "'\n";
var seventhLine = PipeSize5 + " " + PipeMaterial5 + " I.E. " + PipeDirection5 + "=" + Dip5 + "'";
var Mtext = firstLine + secondLine + thirdLine + fourthLine + fifthLine + sixthLine + seventhLine;
var calcsheet = SpreadsheetApp.openById('-removed-').getSheetByName('Calculations');
var ss = SpreadsheetApp.getActiveSpreadsheet(); // ss is now the spreadsheet the script is associated with
var sheet = ss.getSheets()[1]; // sheets are counted starting from 0
// sheet is the second worksheet in the spreadsheet
var cell = sheet.getRange("A1");
cell.setValue(Mtext);
// Dump variable to logger log
// var dump = "Variable dumps: first the URL: " + PNEZD_fileURL + " and next the file ID alone: " + PNEZD_fileID + " and now the job number: " + JobNumber;
// Logger.log( dump );
// Logger.log(JobNumber);
// Logger.log("Data dump: " + PNEZD_field);
// Logger.log("Data dump: " + PNEZD_array[3][3]);
// Logger.log(StructureNumber + "," + Northing + "," + Easting + "," + Elevation);
}

Google Apps Script - Problems with Creating Calendar Event from spreadsheet to non-default calendars

I created a script earlier this year to create a calendar event from a spreadsheet line, putting it onto a shared family calendar and a secondary calendar of my own.
It was running fine earlier this year, but now instead of adding to the secondary calendars, it only adds to my default calendar, which I don't have coded into the script at all.
Did something change with the syntax of how to call a calendar by ID?
//push new events to calendar
function pushToCalendar() {
//spreadsheet variables
var book = SpreadsheetApp.getActiveSpreadsheet();
var now = new Date();
var currentYear = Utilities.formatDate(new Date(now.getTime()), 'America/Chicago', 'yyyy');
var currentSheet = ("Events" + " " + currentYear);
var sheet = book.getSheetByName(currentSheet);
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
var range = sheet.getRange(2,1,lastRow,lastCol);
var values = range.getValues();
//calendar variables
var calendar = CalendarApp.getCalendarById('sample1#group.calendar.google.com');
var calendarShared = CalendarApp.getCalendarById('sample2#group.calendar.google.com');
var numValues = 0;
for (var i = 0; i < values.length; i++) {
//check to see if values 0,1,3,4,5,6 are filled out
if ((values[i][0]) && (values[i][1]) && (values[i][3]) && (values[i][4]) && (values[i][5]) && (values[i][6]))
{
//check if it's been entered before (values[i][8] = '')||(values[i][8] = null)
if (values[i][7].toString().toLowerCase() !== 'y') {
//create event https://developers.google.com/apps-script/class_calendarapp#createEvent
var newEventTitle = 'Game: ' + values[i][0] + ' - ' + values[i][1];
var newSharedTitle = 'Adam - Game: ' + values[i][0] + ' - ' + values[i][1];
var startDay = Utilities.formatDate(new Date(values[i][3]), 'America/Chicago', 'MMMM dd, yyyy');
var startTime = Utilities.formatDate(new Date(values[i][4]), 'America/Chicago', 'HH:mm');
var start = startDay + ' ' + startTime;
var endDay = Utilities.formatDate(new Date(values[i][5]), 'America/Chicago', 'MMMM dd, yyyy');
var endTime = Utilities.formatDate(new Date(values[i][6]), 'America/Chicago', 'HH:mm');
var end = endDay+ ' ' + endTime;
var details = values[i][9] + ' - $' + values[i][10] + '\n' + '\n' + 'Crew: ' + '\n' + values[i][14] + '\n' + values[i][15] + '\n' + values[i][16] + '\n' + '\n' +'Assessor:' + '\n' + values[i][17];
//new event on Secondary AND Shared Calendar
var newEvent = calendar.createEvent(newEventTitle, new Date(start), new Date(end), {location: values[i][13], description: details});
var newSharedEvent = calendarShared.createEvent(newSharedTitle, new Date(start), new Date(end), {location: values[i][13], description: details});
//get ID
var newEventId = newEvent.getId();
//mark as entered, enter ID
sheet.getRange(i+2,8).setValue('y');
sheet.getRange(i+2,9).setValue(newEventId);
}
else;
}
numValues++;
}
Thanks in advance for your help!
Try to create the event and after insert it into your calendar like this:
var event = {
summary:summary,
location: location,
description: '',
start: {dateTime: newdatestart.toISOString()},
end: {dateTime: newdateend.toISOString()},
attendees: [
{email: ''},{email: ''}],
// Red background. Use Calendar.Colors.get() for the full list.
colorId: 11
};
event = Calendar.Events.insert(event, calendarId);
I encountered this same problem with ID as well....apparently you need to get rid of #google.com part of the Event ID itself, and then get it as part of an array
.getId().split('#')[0];
just add this code and it worked like a charm for me