Timezone issue with .createEvent() - javascript

I have issues with the event time zone in my script. I browsed through many topics like this, but my beginner's skills did not allow me to transcribe the solutions to my own case ...
Here's my script:
function book1() {
var form = FormApp.getActiveForm();
var responses = form.getResponses();
var len = responses.length;
var last = len - 1;
var items = responses[last].getItemResponses();
var email = responses[last].getRespondentEmail();
var equipment = items[1].getResponse();
var datestart = items[2].getResponse();
var dateend = items[3].getResponse();
var cal = CalendarApp.getCalendarsByName(equipment)[0];
Logger.log(datestart);
Logger.log(dateend);
var start = new Date(datestart);
var end = new Date(dateend);
Logger.log('start '+start);
Logger.log('end '+end);
var allEvents = CalendarApp.getCalendarsByName(equipment)[0].getEvents(start, end);
if (allEvents.length < 1) {
var event = cal.createEvent(equipment, start, end)
.addGuest(email);
MailApp.sendEmail({
to: email,
subject: "Equipment " +equipment+ " booking confirmed",
htmlBody: "Equipment " +equipment+ " available, please return it by " +dateend+ " and scan the QR code when returning it.",
});
}
else {
var blob = HtmlService.createHtmlOutputFromFile("calendariframe").getBlob();
MailApp.sendEmail({
to: email,
subject: "Equipment " +equipment+ " not available",
htmlBody: blob.getDataAsString(),
});};
}
I can't find the right way to use getTimezoneOffset() or Utilities.formatDate in the right way. Would you have any advice on where to integrate them in my script so that the createEvent() works in GMT+1?
Thank you very much in advance for your help!

Solution found thanks to Cooper!
I went to the scripts project settings, checked the "Show "appsscript.json" manifest file in editor" box, went to the appsscript.json script and changed the timezone ID.

Related

How to send image and charts using mailapp?

I'm trying to send an image and spreadsheet chart in an email together but I can only send one or the other. For example, i can only send images and the chart will not appear and if i send charts the images will not appear. I'm also new to this, thanks for the help.
{
function emailCharts(sheet,emails,emailSubject){
DriveApp.getRootFolder()
var targetspreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Active spreadsheet of the key file
var sheet = targetspreadsheet.getSheetByName('Test'); // Change the sheet name Eg.'IPQC Overall Tracker' to your sheet name
var emailSubject = 'Scratches Awareness Program Test';
var emails = 'example#gmail.com'; // your email ID
var charts = sheet.getCharts();
if(charts.length==0){
MailApp.sendEmail({
to: emails,
subject: "ERROR:"+emailSubject,
htmlBody: "No charts in the spreadsheet"});
return;
}
var emailStarting = "<br>########TEST##########<br>"
var emailEnding = "#################################<br>"
var emailSignature = "<br>Best Regards, <br>############<br><br> This is an automated generated email. No signature is required."
var chartBlobs=new Array(charts.length);
var emailBody="Hi Everyone,<br>" + emailStarting;
var emailImages={};
for(var i=0;i<charts.length;i++){
var builder = charts[i].modify();
builder.setOption('vAxis.format', '#');
var newchart = builder.build();
chartBlobs[i]= newchart.getAs('image/png');
emailBody= emailBody + "<p align='center'><img src='cid:chart"+i+"'></p>" ;
emailImages["chart"+i]= chartBlobs[i];
}
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
var requestData = {"method": "GET",
"headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl =
"https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp
.fetch(googleLogoUrl)
.getBlob()
.setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp
.fetch(youtubeLogoUrl)
.getBlob()
.setName("Scratches Dashboard");
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages:emailImages, attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}],googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob});
}
}
You want to send the images of charts, googleLogoBlob and youtubeLogoBlob as the inline images, and want to send Excel file (xlsx format) as the attachment file.
You want to achieve this using Google Apps Script.
I could understand like this. If my understanding is correct, how about this modification? Please think of this as just one of several answers.
Modification points:
format=xlsx is used for converting Google Spreadsheet to Excel.
{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"} is used as the attachment file.
Please modify to {fileName:sheetName+".xlsx", content:contents, mimeType: MimeType.MICROSOFT_EXCEL}.
googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob is directly used as the object for MailApp.sendEmail(object). And googleLogo and youtubeLogo are not included in the inline images.
Please include those image to the inline images.
When above points are reflected to your script, it becomes as follows.
Modified script:
Please modify your script as follows.
From:
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl =
"https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp
.fetch(googleLogoUrl)
.getBlob()
.setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp
.fetch(youtubeLogoUrl)
.getBlob()
.setName("Scratches Dashboard");
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages:emailImages, attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}],googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob});
}
}
To:
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx"; // Modified
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl = "https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp.fetch(googleLogoUrl).getBlob().setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp.fetch(youtubeLogoUrl).getBlob().setName("Scratches Dashboard");
emailBody += "<img src='cid:googleLogo'><img src='cid:youtubeLogo'>"; // Added
emailImages.googleLogo = googleLogoBlob; // Added
emailImages.youtubeLogo = youtubeLogoBlob; // Added
MailApp.sendEmail({ // Modified
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages: emailImages,
attachments: [{fileName: sheetName+".xlsx", content: contents, mimeType: MimeType.MICROSOFT_EXCEL}],
});
}
Note:
About googleLogo and youtubeLogo, please modify <img src='cid:googleLogo'><img src='cid:youtubeLogo'> for your actual situation.
References:
sendEmail(message)
Enum MimeType
Your code is fine, the only isssue you are having is the way you're building your MailApp.sendEmail() . Do it in this way:
var emails = "example#gmail.com";
var emailSubject = "Test Subject";
var body = emailBody + emailEnding + emailSignature;
var spreadsheetObj = {
fileName:sheetName+".xls",
content:contents,
mimeType:"application//xls"
};
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: body,
attachments: [ spreadsheetObj, googleLogoBlob, youtubeLogoBlob]
});
The attachments must be an array, you were building it in the wrong way. As the Docs says:
attachments BlobSource[] An array of files to send with the email (see example)
Notice:
If you attach several files, the email can take some time to be delivered.

Google Script email send ignoring #N/A values in row

Essentially i'm also pulling email addresses from a separate sheet via a formula so that when new form entry is made, column B populates the proper email (name is included in the form). The problem I'm facing is that for the tool to be efficient I need to run the formula all the way down indefinitely so that when new entry comes it simply looks up the name and column B pulls the correct email address. However, the below code returns an error because it cannot handle #N/A where no email exists yet or even "" with IFERROR in the formula.
Ideally the code will stop if #N/A is encountered and only continues when there is an email in CurrentRow[1] has an email. The code works perfectly fine if empty rows are totally blank.
The current version here comes from what I've read and researched, including the post: Email only new rows in Google sheets. I've researched and lots of similar examples exist but having tried 40 or so variations i could not get mine to work.
function sendEmail() {
//setup function
var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var StartRow = 2;
var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
var WholeRange = ActiveSheet.getRange(StartRow,1,RowRange,11);
var AllValues = WholeRange.getValues();
var message = "";
//iterate loop
for (i in AllValues) {
//set current row
var CurrentRow = AllValues[i];
//define column to check if sent
var KamEmail = CurrentRow[1];
//if row has been sent, then continue to next iteration
if (CurrentRow[1] == "#N/A") {break;}
else;
//set HTML template for information
message +=
"<p>Hi " + CurrentRow[1] + "</p>" +
"<p>Your constituent has submitted an Agenda blog pitch" + "</p>" +
"<p><b>Name of constituent: </b>" + CurrentRow[2] + "</p>" +
"<p><b>Submission Snapshot: </b>" + CurrentRow[3] + "</p>" +
"<p><b>Link to Submission: </b>" + CurrentRow[4] + "</p>" +
"<p><b>Date of Submission: </b>" + CurrentRow[7] + "</p><br><br>";
//set the row to look at
var setRow = parseInt(i) + StartRow;
//mark row as "sent"
ActiveSheet.getRange(setRow, 9).setValue("Sent to KAM");
}
//define who to send grants to
var SendTo = CurrentRow[1];
//set subject line
var Subject = "RE: Registrations";
//send the actual email
MailApp.sendEmail({
to: SendTo,
cc: "",
subject: Subject,
htmlBody: message,
});
}

Fixing Syntax Error, on my Script Editor

function sendEmails(e){
var UserName = e.values[3];
var UserEmail = e.values[5];
var date = e.values[0];
var pin = e.values[4];
var subject = "[LFR] Application Succeed!";
var bodymessage = "Hi" + UserName + "for sending in your job application."
<br>
<br> + "The following is your Purchase Log Pin"
<br> + pin;
var emailsent = "Email Sent";
var isEmailsent = e.values[6];
if (isEmailsent ! = emailsent);
MailApp.sendEmail(UserEmail, subject, bodymessage);
}
The error message always shows, "Illegally formed XML syntax. (line 18, file "Code"). Someone please help me to fix it!
change this
var bodymessage = "Hi" + UserName + "for sending in your job application."
<br>
<br> + "The following is your Purchase Log Pin"
<br> + pin;
to
var bodymessage = "Hi" + UserName + "for sending in your job application.<br> <br>The following is your Purchase Log Pin<br>" + pin;
bascially, your string is not formed correctly
Also,
remove ; after the if statement
if (isEmailsent ! = emailsent)
{
MailApp.sendEmail(UserEmail, subject, bodymessage);
}

Get live currency exchange rates in Cordova

Ok so I'm trying to build a live currency converter app using Cordova and for now just display the exchange as an alert upon opening the app. at the moment i'm not getting anything. i've found many tutorials in different languages but no javaScript that has a simple solution to my problem. any help would be great. thanks
getRate: function ()
{
$from = 'USD';
$to = 'INR';
var script = document.createElement('script');
script.setAttribute('src', "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s="+ $from + $to +"=parseExchangeRate");
document.body.appendChild(script);
},
parseExchangeRate: function(data)
{
var name = data.query.results.row.name;
var rate = parseFloat(data.query.results.row.rate, 10);
alert("Exchange rate " + name + " is " + rate);
},

onFormSubmit trigger not working for sending out email upon form submission

I have a piece of code here which, on form submission, is supposed to:
Perform some calculations in a spreadsheet using the form responses, create a pdf file containing the user's results, and email this to them.
I have set up a trigger which runs "onFormSubmit", with events "From Spreadsheet", "onFormSubmit" and Here is my code:
//Set out global variables
var docTemplate = "1Ff3SfcXQyGeCe8-Y24l4EUMU7P9TsgREsAYO9W6RE2o";
var docName="Calculations";
//createOnFormSubmitTrigger();
function onFormSubmit(e){
//Variables
var ssID = '1dMmihZoJqfLoZs9e7YMoeUb_IobW4k6BbOuMDOTTLGk';
var ss = SpreadsheetApp.openById(ssID);
ss.setActiveSheet(ss.getSheetByName("Sheet3"));
var totalOutstandingPrincipalDebt = SpreadsheetApp.getActiveSheet().getRange("G25").getValue();
var totalOutstandingInterest = SpreadsheetApp.getActiveSheet().getRange("H25").getValue();
var totalOutstandingCompensation = SpreadsheetApp.getActiveSheet().getRange("I25").getValue();
var dailyInterestRate = SpreadsheetApp.getActiveSheet().getRange("J25").getValue();
var grandTotal = SpreadsheetApp.getActiveSheet().getRange("K25").getValue();
var userEmail = SpreadsheetApp.getActiveSheet().getRange("H24").getValue();
//Template Info
var copyId=DriveApp.getFileById(docTemplate).makeCopy(docName+' for '+userEmail).getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
//Putting the data into the file
copyBody.insertParagraph(1,'Total Outstanding Principal Debt: £' + totalOutstandingPrincipalDebt);
copyBody.insertParagraph(2,'Total Outstanding Interest: £'+ totalOutstandingInterest );
copyBody.insertParagraph(3,'Total Outstanding Compensation: £'+ totalOutstandingCompensation);
copyBody.insertParagraph(4,'Grand Total: £' + grandTotal);
copyBody.insertParagraph(5,'Daily Interest Rate: £'+ dailyInterestRate);
copyDoc.saveAndClose();
//email pdf document as attachment
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var subject = "Calculations";
var body = "Thank you very much for using our online calculator. Please find your results attached.";
MailApp.sendEmail(userEmail, subject, body, {htmlBody: body, attachments: pdf});
//Deletes temporary Document
DriveApp.getFileById(copyId).setTrashed(true);
}
The script will sometimes run fine when I am in the script editor (not always?!), but when I submit a form, I receive the following error notification: "Failed to send email: no recipient (line 40, file "Code")", where line 40 is the line:
MailApp.sendEmail(userEmail, subject, body, {htmlBody: body, attachments: pdf});
I have tried using getNote() instead of getValue() for the userEmail variable but that didn't work either! I have also made sure the cell reference on the spreadsheet is formatted as plain text rather than as a number, but I'm not sure what else to try now! Any suggestions would be greatly appreciated!
Thanks so much in advance :)
It's working now since I changed:
var ssID = '1dMmihZoJqfLoZs9e7Y.............';
var ss = SpreadsheetApp.openById(ssID);
ss.setActiveSheet(ss.getSheetByName("Sheet3"));
var totalOutstandingPrincipalDebt = SpreadsheetApp.getActiveSheet().getRange("G25").getValue();
var totalOutstandingInterest = SpreadsheetApp.getActiveSheet().getRange("H25").getValue();
var totalOutstandingCompensation = SpreadsheetApp.getActiveSheet().getRange("I25").getValue();
var dailyInterestRate = SpreadsheetApp.getActiveSheet().getRange("J25").getValue();
var grandTotal = SpreadsheetApp.getActiveSheet().getRange("K25").getValue();
var userEmail = SpreadsheetApp.getActiveSheet().getRange("H24").getValue();
to:
var ssID = '1dMmihZ.................';
var ss = SpreadsheetApp.openById(ssID);
var sheet = SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);
var totalOutstandingPrincipalDebt = sheet.getRange("G25").getValue();
var totalOutstandingInterest = sheet.getRange("H25").getValue();
var totalOutstandingCompensation = sheet.getRange("I25").getValue();
var dailyInterestRate = sheet.getRange("J25").getValue();
var grandTotal = sheet.getRange("K25").getValue();
var userEmail = sheet.getRange("H24").getValue();

Categories

Resources