I am trying to do automate send email to multiple sender(10 emails) with different PDFs(10). Is there a way to attach a pdf in the spreadsheet column next to email address? Then send email with sales quote in pdf as attachment. Is this can be done in JS in google sheet.
Appreciate if someone help me out.
If you're using Google Sheets it's possible, but you have to get creative. In fact you can send emails, with javascript, from google sheets using google scripts. I think if you get creative with a hidden sheet in the same workbook, have a formula populate that sheet with the layout of the PDF, then export that sheet as a PDF to attach to the email... it's doable.
You may find some inspiration here.
Basic send email from google sheets example here.
So, JavaScript runs in the client side. It means that your code is running the user browser. In a brief, you can't send emails just using JavaScript. You're going to need a server to do that.
For example, you may use Spring Boot with Java that already has a lot implemented method that makes your task, i.e, sending an email, super easy.
Have a look at http://spring.io/projects/spring-boot
You can do this by following the below steps,
Uploading the 10 attachments on one google drive folder
On your google sheet add the below script to get the file id
function listFilesInFolder() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("FileID").activate(); //The name of the google sheet is FileID in my case
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow(["File Name", "File-Id"]);
//change the folder ID below to reflect your folder's ID (look in the URL when you're in your folder)
var folder = DriveApp.getFolderById("*[Enter Folder ID here]*");
var contents = folder.getFiles();
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
data = [
file.getName(),
file.getId(),
];
sheet.appendRow(data);
}
}
Build a simple script to send emails and have your 10 emails on one column and all the File IDs generated from the above code on the next column. Below is a sample script to send emails from spreadsheets,
function sendEmails() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Emails").activate(); // Emails is the sheet which has the email and File ID columns
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue(); // Template is the sheet which has my email body
for (var i = 2;i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue(); //Email IDs are on the first column for me
var currentAttachment = ss.getRange(i, 2).getValue(); //Assuming your File IDs are on the second column
var waiver = DriveApp.getFileById(currentAttachment);
var liabilityWaiver = waiver.getAs(MimeType.PDF);
MailApp.sendEmail(currentEmail, subjectLine, messageBody, {attachments:[liabilityWaiver],
cc:'abc#abc.com'}); // the cc is in case you want to CC someone else on the email
I hope this helps!
Related
So I have a google app script where I search a mail based on subject line and then take that csv and update it in an google sheet. This worked fine the first time. But going forward when I got emails with the same subject line it still pick the content of the first email and not the latest .How can I fetch data from the latest mail.
function importCSVFromGmail() {
var threads = GmailApp.search("email subject);
var message = threads[0].getMessages().slice(-1);
Log.logger(message);
var attachment = message.getAttachments()[0];
Log.logger(message.getAttachments()) ;
// Is the attachment a CSV file
if (attachment.getContentType() === "text/csv") {
var sheet = SpreadsheetApp.getActiveSheet();
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
// Remember to clear the content of the sheet before importing new data
sheet.clearContents().clearFormats();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
}
You should be able to get the last or most recent message like that :
var message = threads[0].getMessages().slice(-1)
So I am trying to log files (and their Id) from my Drive to a spreadsheet using Google Apps Script. The problem is that I don't know how to add content to rows of a Google Sheets document.
I know how to log my files and their Id:
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
Logger.log(file.getId());
}
Now I would like to log the Name and Id of my files from one folder to a Google sheet. Does anybody know how to achieve this?
You'll need to get the spreadsheet, and add the file names to a 2D array. The following code requires you to enter the spreadsheet file ID and the sheet tab name.
function logFilesToSheet() {
var arrayForOneRow,file,id,name,outerArray,sh,ss;
id = "";//Enter your spreadsheet file id here
name = "";//Enter the sheet tab name here
ss = SpreadsheetApp.openById(id);
sh = ss.getSheetByName(name);
outerArray = [];
var files = DriveApp.getFiles();
while (files.hasNext()) {
file = files.next();
//Logger.log(file.getName());
//Logger.log(file.getId());
arrayForOneRow = [];//Reset on each loop - Each row needs a new array
arrayForOneRow.push(file.getName());
arrayForOneRow.push(file.getId());
outerArray.push(arrayForOneRow);
}
sh.getRange(sh.getLastRow() + 1,1,outerArray.length,2).setValues(outerArray);
}
Looking for help compiling a code to merge PDF files with the same name in Google Documents. I have a script that saves a spreadsheet as a PDF with a name which is a formatted date. That said, there could be up to 7 with the same name. I need to merge these into 1 PDF but I need to do it automatically set up on a weekly trigger.
Anything helps. Thank you!
This combines the text of all PDF's in a folder
function combinePDFs() {
var folder=DriveApp.getFolderById('1Zd_ty0O1WljjADzGQGrtUM57hvE5berT');
var destFolder=DriveApp.getFolderById('1mHRFCwzqccJn83N7THnvZ8_Z-DCLeGOV');
var files=folder.getFilesByType(MimeType.PDF);
var text='';
while(files.hasNext()) {
var file=files.next();
var blob=file.getBlob();
var resource={title:blob.getName(),mimeType:blob.getContentType()}
var f=Drive.Files.insert(resource, blob, {ocr: true,ocrLanguage: "en"});
var doc=DocumentApp.openById(f.id);
text+=doc.getBody().getText() + '\n------------------------------------------------------------\n';
DriveApp.getFileById(f.id).setTrashed(true);//trash intermediate files
}
var tf=DocumentApp.create('combined.doc');
tf.getBody().setText(text);
tf.saveAndClose();//combined text file
var docblob=DocumentApp.openById(tf.getId()).getAs('application/pdf');
docblob.setName('combined.pdf');//
destFolder.createFile(docblob);//combined PDF
DriveApp.getFileById(tf.getId()).setTrashed(true);//trashed combined text file
}
Reference from Amit Agarwal
Drive.Files.insert
Setup a Time Based Trigger
Upload files with Google Apps Script
I want the user to be able to write information to a master sheet. I'm able to get the user to write to it by sharing the master sheet. However, I don't want them to really have access to view it. Is there any work-around this?
function writeRecords(currentSheet) {
// get current sheet
var currentLastRow = currentSheet.getLastRow();
var currentRange = currentSheet.getRange(2, 1, currentLastRow, 6);
var currentValues = currentRange.getValues();
// get master sheet
var masterSpreadSheet = SpreadsheetApp.openById("fakesheetid")
var masterSheet = masterSpreadSheet.getSheetByName('Sheet1');
var masterLastRow = masterSheet.getLastRow();
// need to insert into master spreadsheet startin from its last row
masterSheet.getRange((masterLastRow + 1), 1, currentLastRow, 6).setValues(currentValues);
}
Create a web app that run as you.
Related
HOW TO modify a google spreadsheet from collaborators that aren't editors?
Perhaps you should consider using Google Forms?
Google Forms allows you to set up an interface to gather information from a user and use a Google Sheet as the repository for which this information is dumped into.
this is the first script i try to write from scratch. It's been no good up to now so i'm going to ask for some help.
Case: I recieve e-commerce confirmation emails from e-commerce sites no reply email address. In the email's body they send email address from buyers. I want to send an automated mail to the body's email address.
How i plan to do this (any suggetions to eliminate steps will be thanked).
Use a rule to tag incoming emails with a unique tag.
Use that tag to identify emails in gmail with a script, go one by one and extract the info i need. Use regex with the emails body content to extract the email address i need to send the automated emails. Plan is to get: subject, date, email from body.
Write all that info to a spreadsheet.
Get rid of unique tag info to prevent duplicate runs.
Then use form mule addon to send emails from the spreadsheet.
So far, i've dealt with steps 1 (easy), and been stuggling with steps 2 and 3 (im not a coder, i can read, undestrand and hack. writing from scratch is a completely different thing). Ive dealt with 4 before i think this is the best way to deal with it.
With the script i extract info to the spreadsheet, with the addon i use the info from the spreadsheet to send emails.
This is the code ive written so far. I've left the regex part for later cause i cant even write anything into the spreadsheet yet. once i get that working, ill start working in the regex and "remove the label" aspects of the script.
function myFunction() {
function getemails() {
var label = GmailApp.getUserLabelByName("Main tag/subtag");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
var messages=threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var message=messages[j];
var subject=message.getSubject();
tosp(message);
}
}
}
function tosp(message){
var body=message.getBody()
var date=message.getDate();
var subject=message.getSubject();
var id= "my spreasheet id";
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getActiveSheet();
sheet.appendRow(subject,date,body);
}
}
Any help would be appreciated.
Thanks
Sebastian
Following is the code I wrote and tested that performs the steps 2, 3 and 4 mentioned by you perfectly well.
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var msg = messages[j].getBody();
var sub = messages[j].getSubject();
var dat = messages[j].getDate();
ss.appendRow([msg, sub, dat])
}
threads[i].removeLabel(label);
}
}
One of the faults in your code was that the appendRow function accepts an array of elements specified within [ ] brackets.
Depending on where you're attaching this script, your line of code:
var ss = SpreadsheetApp.openById(id);
is not necessary if the script is being written in the script editor of the Spreadsheet where you want these emails to be logged. However, if there are multiple sheets in that spreadsheet, you can replace my line
var ss = SpreadsheetApp.getActiveSheet();
by
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
Another suggestion is that the current code will give you messages in HTML format. Hence, if you want to get the message in plain text as you see it, use:
var msg = messages[i].getPlainBody();
Now you can write another function for regex and pass the message msg to that. Hope this helps!
I made a ready-to-use script, explaining how to use it (from the start) as well, for those who need more assistance.
It's on gmail-to-google-sheets-script repository. Just read the content and follow the instructions.
How to use
Create a new Google Sheet
Access menu Tools > Script Editor
Copy the content from gmailt-to-sheets.gs to editor, replacing the sample code there
Replace the value on SEARCH_QUERY to your real query (Do your search on gmail first, copy and paste the search terms there)
Select saveEmails on menu (near "run" and "debug" buttons)
Click on "Run" button
It will ask for authorization at first run, proceed accepting it (it's your Gmail account authorizing your Google Script account)
After run, the results will be applied to you sheet
Changing fields
If you want to save different message attributes, take a look at gmail-message class and change your script file the code below comments with a ✏️ (pencil).