Google App Script - Send email with current time

I need to create a function in AppScripts that sends an email to my email with the current time. Later, I have to create a trigger that forces the function to run once every hour. I know it will be very easy for the majority of you, but I am starting with coding and I am stuck with this exercise.

This is what I´ve written:

function sendemail(){

function getDate() {
  var d = new Date();
  return (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear();
}

function getTime() {
  var d = new Date(),
      offset = -d.getTimezoneOffset()/60,
      h = d.getUTCHours() + offset,
      m = d.getMinutes(),
      s = d.getSeconds();
  return h + ":" + m + ":" + s;
}

function getDateAndTime() {
   return getDate() + " " + getTime();

  Gmail.sendEmail({
     to: "[email protected]",
     subject: "Hora actual",
     htmlBody: "La hora actual es +dateofDay <br/> Regards, Your robot",
   });
}

}

But it doesn´t work. I´m getting a bit frustrated and the same error appears all the time: "Script function not found: doGet".

Can anyone have a look at it and help me?

Thanks in advance, very appreciated.

Best regards, Luis

Upvotes: 1

Views: 1738

Answers (1)

Dean Ransevycz
Dean Ransevycz

Reputation: 953

Web apps need a doGet(e) or doPost(e) function to accept input from the web page via the url (doGet()) or post data (doPost()). The parameter e in each of these functions is the 'event object' where the url/post data are passed in. So, you'll need to call your email-sending & date-generating functions from doGet().

Here's a high-level view of the logic:

function doGet(e){
  var d = new Date();
  var date = getGate(d); // your getDate() function
  var time = getTime(d); // your getTime() function
  var datetime = date + " " + time;
  sendEmail(datetime); // a new function to send an email
}

That said, you could get your timestamp much more efficiently with Utilities.formatDate(new Date()) (documentation here) get your date & time in the correct timezone & with the correct locale formatting.

With sending email, your could use the basic Mail service function MailApp.sendEmail(recipient, subject, body), which sends an email to the recipient, with the subject you pass in & the message specified in body. This appears to be all you need in this context. If you need to interact with the mailbox, then you should use the Gmail service, but if you just need to send an email from the account running the we app, stick to the Mail service.

Upvotes: 1

Related Questions