How to send a notification email at 1 pm and 6 pm? - triggers

I know how to send an email to someone but I do not know how to send it at a certain time.
Can you help me ?
// My code is (scriptClient) :
function sendEmailClient(){
var user = app.pages.pageEmprunt.descendants.TextBox2.value;
google.script.run
.withSuccessHandler(function(){
})
.withFailureHandler(function(err){
console.error('erreur');
})
.sendEmail(user);
}
// And in scriptServer is:
function sendEmail(user){
var htmlBody =
"Bonjour!<br/><p>Vous avez emprunter une ou plusieurs clé(s).<br/>"+
"<b>N'oubliez pas de la ou les ramener et de signer le registre.</b><br/></p>"+
'Merci';
var emailObj = {
to : user,
subject : 'Remise des clés',
htmlBody : htmlBody,
noReplay: true
};
MailApp.sendEmail(emailObj);
}

You can save the users to whom the emails should be sent on a database and then get the users from the database using another function and keep looping over sendEmail(user) and inject each user as a parameter. Lets call this function as fetchAndSendEmails(). Now create a trigger which calls this function at 1pm and 6pm everyday like below. All of this should be written in server script.
ScriptApp.newTrigger("fetchAndSendEmails").timeBased().atHour(13).create();
ScriptApp.newTrigger("fetchAndSendEmails").timeBased().atHour(18).create();

Related

Send an email using email addresses from a column in Google sheets

I'm trying to create code that will send an email using addresses from a specific column in google sheets. I want the code to send an email after the sheet is edited by other users. For example, someone enters a request on a row in the sheet - then an email is sent to the manager of the request. Here's what I have so far...
function SendEmail(){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HLP REQUESTS").getRange("K:K");
var emailAddress = emailRange.getValues()[0][0];
// Send Alert Email.
var message = 'A request has been submitted for professional learning related to an HLP you champion. Please check the Design Team Notes document in case follow-up is required.'; // Second column
var subject = 'HLP Request for Professional Learning';
MailApp.sendEmail(emailAddress, subject, message);
}
When I run the code above I get an error - Exception: Failed to send email: no recipient. There is a valid email address in column K, so I'm a little confused.
If you want get email address from the last cell of the column K it can be done this way:
function SendEmail(){
var emailRange = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("HLP REQUESTS").getRange("K:K");
var emailAddress = emailRange.getValues()
.flat() // convert a 2d array into a flat array
.filter(String) // remove empty elements from the array
.pop(); // get the last element from the array
var message = 'A request has been submitted for professional learning related to an HLP you champion. Please check the Design Team Notes document in case follow-up is required.';
var subject = 'HLP Request for Professional Learning';
MailApp.sendEmail(emailAddress, subject, message);
}
Update
Here is the full implementation with installable trigger onEdit that sends email as soon as the checkbox (in column L) was checked in:
// global variables
var SS = SpreadsheetApp.getActiveSpreadsheet(); // get the srpreadsheet
var checkbox_col = 12; // column with checkboxes (L in this case)
// the main function
function sendEmail(e) {
try {
var {rowStart, columnStart} = e.range; // get row and column of the cell that was edited
if (columnStart != checkbox_col) return; // do nothing if it was not column with checkboxes
if (e.value != 'TRUE') return; // do nothing if the checkboxs was unchecked
e.range.setValue(false); // else uncheck the chekbox
var sheet = SS.getSheetByName('HLP REQUESTS'); // get the sheet
var emailAddress = sheet.getRange('K' + rowStart).getValue(); // get email addres from current row, column K
var message = 'A request has been submitted for professional learning related to an HLP you champion. Please check the Design Team Notes document in case follow-up is required.';
var subject = 'HLP Request for Professional Learning';
MailApp.sendEmail(emailAddress, subject, message); // send the message
SS.toast('Email to ' + emailAddress + ' has been sent');
}
catch(e) { SpreadsheetApp.getUi().alert(e) }
}
// additional functions -------------------------------------------------------------------------
// insatll the trigger
function install_onEidt_trigger() {
ScriptApp.newTrigger('sendEmail').forSpreadsheet(SS).onEdit().create();
SS.toast('Trigger was installed');
}
// remove all triggers
function remove_all_triggers() {
ScriptApp.getProjectTriggers().forEach(t => ScriptApp.deleteTrigger(t));
SS.toast('All triggers were remoded');
}
// custom menu to install and remove triggers
function onOpen() {
SpreadsheetApp.getUi().createMenu('⚙️ Scripts')
.addItem('Install trigger', 'install_onEidt_trigger')
.addItem('Remove all triggers', 'remove_all_triggers')
.addToUi();
}
To make it work you have:
to reload the spreadsheet (or to run the function onEdit() manually) to get the custom menu Scripts
in the custom menu run the item Install trigger
after that it will try to send the message to the address from column K of current row whenever user clicks on checkbox in column L
My test sheet looks like this:
Sending Emails
function SendEmail() {
const ss = SpreadsheetApp.getActive();
const rsh = ss.getSheetByName("HLP REQUESTS");
const emails = rsh.getRange("K1:K" + rsh.getLastRow()).getDisplayValues().flat();
var message = 'A request has been submitted for professional learning related to an HLP you champion. Please check the Design Team Notes document in case follow-up is required.';
var subject = 'HLP Request for Professional Learning';
emails.forEach(e => {
MailApp.sendEmail(e, subject, message);
});
}
If you wish to attach this to an onEdit you will have to rethink the process because the onEdit trigger fires on every edit to any sheet and most likely you will be require to use an installable onEdit so that you can perform operations that require permission. I'd recommend you play around with the onEdit simple trigger for a while. Look at the event object and see what's available at low overhead cost.

Google Sheets App Script- Add signature when sending e-mail

I'm working on a script that will save my Google Sheet spreadsheet as a pdf and email it as an attachment. The code I'm using works, but I don't know how to add a signature to the email I'm sending. Is this possible, and if so; what would be the cleanest way to do it? Here's the code I'm working with. I know, it's not pretty.
function displayPrompt() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheetName = ss.getActiveSheet().getName();
var ui = SpreadsheetApp.getUi();
var result = ui.prompt("Please enter email body");
//Get the button that the user pressed.
var button = result.getSelectedButton();
var message = {
to: "someone#somewhere.com",
subject: sheetName,
body: "Hi team,\n\nPlease find attached the quote that you requested.\n" +
result.getResponseText() + "\nThank you,\nMe",
name: "My Name",
attachments:
[SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
if (button === ui.Button.OK) {
Logger.log("The user clicked the [OK] button.");
Logger.log(result.getResponseText());
MailApp.sendEmail(message);
} else if (button === ui.Button.CLOSE) {
Logger.log("The user clicked the [Cancel] button.");
}
}
I believe your goal as follows.
You want to add the signature to the message of Gmail using MailApp.sendEmail
In this case, I think that there are 2 patterns.
Pattern 1:
In this pattern, by declaring the signature as the variable, the signature is added.
Sample script:
Please modify message in your script as follows.
var signature = "\nsample signature"; // Added
var message = {
to: "someone#somewhere.com",
subject: sheetName,
body: "Hi team,\n\nPlease find attached the quote that you requested.\n" + result.getResponseText() + "\nThank you,\nMe" + signature, // Modified
name: "My Name",
attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
Pattern 2:
In this pattern, by retrieving the sigunature of Gmail, the signature is added.
Sample script:
In this sample, Gmail API is used. So, before you use this script, please enable Gmail API at Advanced Google services. And, please modify message in your script as follows.
var signature = "<br>" + Gmail.Users.Settings.SendAs.list("me").sendAs[0].signature; // Added
var message = {
to: "someone#somewhere.com",
subject: sheetName,
htmlBody: ("Hi team,\n\nPlease find attached the quote that you requested.\n" + result.getResponseText() + "\nThank you,\nMe").replace(/\n/g, "<br>") + signature, // Added
name: "My Name",
attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
The signature retrieved from Gmail is HTML. So in this pattern, htmlBody is used instead of body.
References:
Method: users.settings.sendAs.list

Flutter/Dart socket communication, characters encoding issue

For a proof of concept where 2 applications, written in Flutter and running on the same device, need to exchange information, I am using the 'dart:io' Sockets.
One of the 2 applications implements a SocketServer to receive the information and the other initializes the sockets communication.
From a connection perspective, this is working fine, using the following code:
Code of the server:
ServerSocket.bind('127.0.0.1', 8080).then((ServerSocket socketServer) {
socketServer.listen((Socket socket) {
socket.listen((List<int> data){
String result = String.fromCharCodes(data);
print('received: $result');
});
});
}).catchError(print);
Code of the client:
Socket.connect('127.0.0.1', 8080).then((socket) {
String data = 'Les élèves regardent par la fenêtre';
socket.write(data);
print("sent: $data");
}).catchError(print);
However, when I try to send a String which contains accentuated characters, I have the following outcome:
sent: Les élèves regardent par la fenêtre
received: Les élèves regardent par la fenêtre
This looks like an encoding related issue but I haven't yet been able to solve it.
Would anybody have any idea how to proceed to have this working?
Thanks
I found the solution.
Here it is:
Code for the Client:
Socket.connect('127.0.0.1', 8080).then((socket) {
String data = 'Les élèves regardent par la fenêtre';
socket.encoding = utf8; // <== force the encoding
socket.write(data);
print("sent: $data");
}).catchError(print);
Code for the Server:
ServerSocket.bind('127.0.0.1', 8080).then((ServerSocket socketServer) {
socketServer.listen((Socket socket) {
socket.listen((List<int> data){
String result = utf8.decode(data);
print('received: $result');
});
});
}).catchError(print);
The solution consists of "forcing" the encoding to utf8
Thanks for your help.
You should try using ut8.encode when writing the data, and utf8.decode when reading it on the other side.

Google Form mail notification script. Emails always have "me" as sender

I have tried to use the search function, but did not find a solution for my problem, or I do not understand enough yet.
I have written a script for google forms, that sends an automatic email to two email addresses, when an user submits the form. I have build in some information that should show in the email subject and puts the input from the forms into the email, with some simple HTML formatting.
My problem is, that the emails always have my Email address as the sender (the account I used for creating the form)
I would like to have the senders email, the one that is submitting the form.
How is that possible?
Here is the code:
function sendFormByEmail(e)
{
// Sent to Email address
var email1 = "123#abc.com";
var email2 = "345#abc.com";
// Variables
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var txt = "";
var subject = "Example text: ";
// Var e = form input as array.
// Loop through the array.
for(var i in headers){
txt += "<b>" + headers[i] + '</b>' + ': '+
e.namedValues[headers[i]].toString() + '<br><br>';
}
// Insert variables from the spreadsheet into the subject.
// Create email subject
subject += "Example text " + e.namedValues[headers[2]].toString();
// Send the email
MailApp.sendEmail(email1, subject, "", {htmlBody:txt});
MailApp.sendEmail(email2, subject, "", {htmlBody:txt});
}
It is not possible to send the mail as the user who submitted the form as the script is running from the user account and the mailapp will send the mail from that account only. you can change the display name according to the user name who submiited the form by the parameter name. Also you can change the email to noreply#domainName.com by adding the parameter noReply in mailApp syntax. However you cannot change it to the user who submitted the form
You can refer this documentation for the above parameters : https://developers.google.com/apps-script/reference/mail/mail-app
Hope this could help

How to send a form to my e-mail by googlescript every tuesday and every thrusday?

First of all I'm completly new at programming so I think my question is really simple but i couldn't find an answer that really matches my issue.
I created a form in googleforms and I want to send this form to my e-mail every tuesday and every thursday by googlescript. (the embed form, not the link)
Firstly, I'm not beeing successful not even sending it to my e-mail.
I tried two methods that I found here but thats what I got:
this is the code im using:
function sendForm(form,email) {
var form = FormApp.getActiveForm();
var email = "myemail#gmail.com"
var formUrl = form.getPublishedUrl();
var url = form.getPublishedUrl();
var response = UrlFetchApp.fetch(url);
var htmlBody = HtmlService
.createHtmlOutput(response)
.getContent()
;
MailApp.sendEmail({
to: email,
subject: "subject",
htmlBody: htmlBody,
});
}
The other code i tried just give me the e-mail message "HtmlOutput" and not the form.
Can someone help me?
Thanks in advance.