Is it possible to automatically send WhatsApp messages if someone fills my google form,currently storing data into a google sheet. In this form, users fill in their Name and phone number. I want to automatically send them a welcome message when they fill the form. I have successfully sent a welcome email in a similar google form with the help of App Script.
This is what I did in case of email:
function sendMail() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CRM").activate()
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var quotaLeft = MailApp.getRemainingDailyQuota();
// Logger.log(quotaLeft)
if((lr-1) > quotaLeft){
Browser.msgBox("You have only " + quotaLeft + " E-mail left, mails were not sent")
} else{
for(var i=2; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue();
var currentSub = ss.getRange(i, 3).getValue();
var currentName = ss.getRange(i, 2).getValue();
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(i, 2).getValue();
var name = templateText.replace("{name}", currentName);
MailApp.sendEmail(currentEmail, currentSub, name)
}
Browser.msgBox("Welcome emails sent")
}
}
It's possible if you use twillo. Try the below code
function sampletTextMessage(){
var ACCOUNT_SID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var ACCOUNT_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var options = {
"method" : "post",
'headers' : {
"Authorization" : "Basic " + Utilities.base64Encode(ACCOUNT_SID + ":" + ACCOUNT_TOKEN),
},
'payload' :{
'Body' : 'Your Twilio code is 1238432',
'To' : 'whatsapp:+91XXXXXXXXX3',
'From': 'whatsapp:+1XXXXXXXXX6',
},
'muteHttpExceptions' : true
};
var url="https://api.twilio.com/2010-04-01/Accounts/" + ACCOUNT_SID + "/Messages.json";
var response = UrlFetchApp.fetch(url,options);
Logger.log(response);
}
Register in https://panel.rapiwha.com/landing/login.php. Link your number and get the API Key.
Put the below code in your sheet
Install a Trigger "On Form Submit"
//
//
function onFormSubmit(e) {
var today=new Date();
var shtname = e.source.getActiveSheet().getName();
switch (shtname) {
case "SaleOrder":
var resp = e.source.getActiveSheet().getRange(e.range.rowStart,1, e.range.rowStart,4 ).getValues();
//name is the first question
//mobile no is second question (with country code, without + sign)
var api_key="xxxxxx"; //from rapiwah
var wup = "Dear " +resp[0][1]+" Thank you for contacting us. We will get back yo you soon";
var formurl2= 'https://panel.rapiwha.com/send_message.php?apikey='+api_key+'&number=' + resp[0][2] +'&text='+wup;
var formurl3 = formurl2.replace(/#/g, "");
var formurl4 = formurl3.replace(/,/g, "");
var formurl = formurl4.replace(/ /g, "%20");
var response = UrlFetchApp.fetch(formurl);
break;
//
default:
break;
}
}
Related
This my mini project.Click here.
Gmail merge with 5 file attachments
Have to send email through google sheets with attachment
Must have email sent time
The requirements is in the image
this coding for mail merge in google sheets.I don't know where to add the file attachment and i don't know how to add.
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").activate();
var lr = ss.getLastRow();
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
var quotaLeft = MailApp.getRemainingDailyQuota();
//Logger.log(quotaLeft);
if ((lr - 1) > quotaLeft) {
Browser.msgBox("You have " + quotaLeft + " left and you are trying to send " + (lr - 1) + " emals.Emails were not send.")
} else {
for (var i = 2; i <= lr; i++) {
var currentEmail = ss.getRange(i, 1).getValue();
var currentClass = ss.getRange(i, 3).getValues();
var currentName = ss.getRange(i, 2).getValues();
var messageBody = templateText.replace("{name}", currentName).replace("{class}", currentClass);
var subjectLine = "Reminder:" + currentClass + " Upcoming Class";
MailApp.sendEmail(currentEmail, subjectLine, messageBody);
}// class for loop
}// class for function
}
Answer
To add an attachment you have to add a fourth parameter called options to the function MailApp.sendEmail. It is an object that can different advanced parameters. To define the attachment you can use the following example:
Code
var options = {
attachments: [file1, file2]
}
MailApp.sendEmail(currentEmail, subjectLine, messageBody, options);
However, I recommend you to use GmailApp.sendEmail. It is more integrated with Gmail and has more functionalities.
update
The image you attach is a bit confusing looking at your code, however, I have edited it so you can see how to perform the task you want in a more optimal way.
Please check the value assignment carefully. As you can see, I only use once the method getRange and getValues to get all the values of a particular row:
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").activate();
var lr = ss.getLastRow();
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
var quotaLeft = MailApp.getRemainingDailyQuota();
//Logger.log(quotaLeft);
if ((lr - 1) > quotaLeft) {
Browser.msgBox("You have " + quotaLeft + " left and you are trying to send " + (lr - 1) + " emals.Emails were not send.")
} else {
for (var i = 2; i <= lr; i++) {
var rowValues = ss.getRange(i, 1, 1, 13).getValues()
var name = rowValues[0]
var organizationName = rowValues[1]
var eventName = rowValues[2]
var email = rowValues[3]
//
var file1 = DriveApp.getFilesByName(rowValues[7]).next()
var file1 = DriveApp.getFilesByName(rowValues[8]).next()
var options = {
attachments: [file1, file2]
}
var messageBody = templateText.replace("{name}", currentName).replace("{class}", currentClass);
var subjectLine = "Reminder:" + currentClass + " Upcoming Class";
MailApp.sendEmail(currentEmail, subjectLine, messageBody, options);
}// class for loop
}// class for function
}
With all this information you should have no problem achieving your goal. If you run into any errors, let me know, but keep in mind that the code is not ready to use.
Reference
MailApp.sendEmail
GmailApp.sendEmail
Sheet: getRange
Sheet: getValues
I'm an Italian (sorry for bad English) system engineer but I accepted to help a friend so I had to achieve this goal.
He's trying to sponsor his products through Telegram but he's stingy and lazy and before investing wants to try something managed by a bot.
So I created the Telegram Bot, used his link of SpreadSheet, and tried to do this thing:
Column U is a link referral to an image and he wants to display that image, column B must be compared with a string and if it's the same then print the column A(integer), F(integer), L(string), J opens a chat with #someone if it's not the same than go to the next line.
As a newbie I past many time reading online and trying to find the way, but I've just reached this:
var token ="myToken";;
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "https://script.google.com/macros/s/myLinkReferal/exec";
var ssId = "MyssId";
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2,2, lastRow-1, lastColumn-1);
function getMe() {
var url = telegramAPI + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramAPI + "/setWebhook?url=" + webAppAPI;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramAPI + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doPost(e) {
Logger.log(e);
for(i = 1; i < lastColumn; i++){
for (j = 1; j < lastRow ; j++){
var cell = searchRange.getCell(1,i).getValue();
if (cell === "DISPONIBILE"){
****visualize a photo taken form a link in datasheet cell Ux
print string taken from Ax
print string taken from Ax**
link to chat with #someone**
}else j=lastRow;
};
};
var text = data.message.text;
var what = data.message.text.split("-")[0]
var who = data.message.text.split("-")[1]
var response = "Hi " + name + ", this quote has been added to your database: " + text;
sendText(id,response);
SpreadsheetApp.openById(ssId).getSheets()[1].appendRow([text,response,what,who]);
}
I have a Google Sheet where the Email & Name columns are auto-fill based on user submitted form. Also, I have 2 more columns where one column contain the list of giveaway code and another column is to act as an approval to send the email.
So for now I manage to create a button where when click it will send all emails with the giveaway code.
Now,
How can I only send the email to the user that only has a value "y" in the Status column?
Also, after sending the emails, the value "y" will changed to "d"? So that later, if I use the function again, it will only sending to the new users.
This is the sheet example https://docs.google.com/spreadsheets/d/1KkShktBnJoW9TmIzNsAuAJb6XslBrMwJGEJu7xeF1fk/edit?usp=sharing
This is the code
function sendArticleCountEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Test1"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:E1000");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var emailAddress = rowData[1];
var timeStamp = rowData[0];
var recipient = rowData[2];
var code = rowData[3];
var status = rowData[4];
var message = 'Dear ' + recipient + ',\n\n' + 'The giveaway code is ' + code;
var subject = 'Here is your giveaway code!';
MailApp.sendEmail(emailAddress, subject, message);
}
}
/**
* The event handler triggered when opening the spreadsheet.
* #param {Event} e The onOpen event.
*/
function onOpen(e) {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: 'Send Emails', functionName: 'sendArticleCountEmails'}
];
spreadsheet.addMenu('Send Emails', menuItems);
}
Just add an if statement like this:
function sendArticleCountEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Test1"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:E1000");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var emailAddress = rowData[1];
var timeStamp = rowData[0];
var recipient = rowData[2];
var code = rowData[3];
var status = rowData[4];
var message = 'Dear ' + recipient + ',\n\n' + 'The giveaway code is ' + code;
var subject = 'Here is your giveaway code!';
if (status == "y") {
MailApp.sendEmail(emailAddress, subject, message);
var actualRow = parseInt(i)+2;
sheet.getRange(actualRow,5).setValue("d");
}
}
}
With my spreadsheet, I have 2 Google forms tied to 2 sheets. When a form gets submitted the script executes and does it's thing. However, I only want the script to execute based on a submission from a single sheet. As it is now, the script executes when either of the forms get submitted.
My two sheets are:
Job Submission
and Order Submission
Any advice?
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
var printerId = "";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017","10/09/2017","11/23/2017","12/24/2017","12/25/2017","01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 );
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
//Get information from form and set as variables
var email_address = "";
var job_name = values[1];
var order_count = values[2];
var order_form = values[7];
var print_services = values[3];
var priority = values[5];
var notes = values[6];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyOrderForm', order_form);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission - " + job_name;
var body = "Here is the work order for " + job_name + ". Job is due " + expirationDate + ".";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
var newDocName = docName + ' for ' + job_name;
return [copyId, newDocName];
}
function printGoogleDocument(copyId, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid" : "",
"content" : copyId,
"title" : docName,
"contentType" : "google.kix", // allows you to print google docs
"ticket" : JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName= returnedDocValues[1];
printGoogleDocument(copyId, docName);
}
Edit:
I'm not sure how to do a complete or verifiable example since it's dependent on the form submission. I don't often work with javascript so I'm still learning.
Anyway, I updated my onFormSubmit function, however, my other functions have failed to execute. The script doesn't create the doc and in turn doesn't get sent to the google cloud print
// When Form Gets submitted
function onFormSubmit(e) {
// Initialize
var rng = e.range;
var sheet = rng.getSheet();
var name = sheet.getName();
// If the response was not submitted to the right sheet, exit.
if(name != "Job Submission") return;
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName= returnedDocValues[1];
printGoogleDocument(copyId, docName);
}
If your onFormSubmit function is on a script bounded to the spreadsheet, the event object includes a range object. You could use getSheet to get the sheet and then getName to get the sheet name.
Example:
function onFormSubmit(e){
// Initialize
var rng = e.range;
var sheet = rng.getSheet();
var name = sheet.getName();
// If the response was not submitted to the right sheet, exit.
if(name != "Responses 1") return;
//Otherwise continue
}
Going off of Ruben's suggestion, here is what I ended up with
function onFormSubmit(e) {
// Initialize
var name = e.range.getSheet().getName();
// If the response was not submitted to the right sheet, exit.
if (name != "Job Submission") return;
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName = returnedDocValues[1];
printGoogleDocument(copyId, docName);
}
I'm wondering if anyone has already put together a script that simply takes a phone number from a cell and sends a text message. Just the same as if it were an email address. Using the carriers email extension is not the solution I'm looking for but if someone has figured out how to programmatically figure out the carrier extension, add it to the phone number, then that would work too.
Example I'm using for sending an email
function inventory() {
var sheet = SpreadsheetApp.getActiveSheet()
var row = sheet.getActiveRange().getRowIndex()
var firstName = sheet.getRange(row, getColIndexByName("First Name")).getValue();
var lastName = sheet.getRange(row, getColIndexByName("Last Name")).getValue();
//var phone = sheet.getRange(row, getColIndexByName("Phone Number")).getValue();
var email = sheet.getRange(row, getColIndexByName("Email Address")).getValue();
var inventoryLinks = sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
//var userEmail = 'put email here';
var subject = "Your Inventory List";
var body = "Hello"
+ "\n\n" + "Please follow the supplied links below to see the listings that fit your profile."
+ "\n\n" + sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
MailApp.sendEmail(email, subject, body, {name:"Inventory List"});
}
function getColIndexByName(columnName) {
var sheet = SpreadsheetApp.getActiveSheet();
var numColumns = sheet.getLastColumn();
var row = sheet.getRange(1, 1, 1, numColumns).getValues();
for (i in row[0]) {
var name = row[0][i];
if (name == columnName) {
return parseInt(i) + 1;
}
}
return -1;
}
So I want to accomplish the same thing replacing the email address with a phone number
This is what I ended up with. Works Great!
function sendSMS() {
// Get account SID and auth token here:
// https://www.twilio.com/user/account
// Also, you have to buy a paid account to send SMS to any phone number. Otherwise you can only send to verified numbers
// So this script allows me to put my cursor in the row I want to send an SMS.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var phone = sheet.getRange(row, getColIndexByName("Phone")).getValue();
var inventoryLinks = sheet.getRange(row, getColIndexByName("Inventory Links")).getValue();
var sentSMS = sheet.getRange(row, getColIndexByName("Sent SMS")).getValue();
var comments = sheet.getRange(row, getColIndexByName("Comments")).getValue();
var activeUser = Session.getActiveUser().getEmail();
var extphone = "+1" + phone;
var body = "Click on the link/s to see current inventory. " + inventoryLinks;
var accountSid = "get it from your Twilio account";
var authToken = "get it from your Twilio account";
var url = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/SMS/Messages.json";
var options = {
method: "post",
headers: {
Authorization: "Basic " + Utilities.base64Encode(accountSid + ":" + authToken)
},
payload: {
// From is one of your Twilio phone numbers
From: "Put you Twilio number here",
To: extphone,
Body: body
}
};
sheet.getRange(row, getColIndexByName("Sent SMS")).setValue('Sent SMS').setComment(new Date() + activeUser);
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}