Paste image in email before sending, google app scripting - google-apps-script

Google App scripts noob here. I am trying to send email from google sheets and I have a working code. However, the challenge I have unaddressed is to paste an image in the email before sending it. The image that needs to be pasted is copied from the snipping tool. In Microsoft Outlook, I have used .Show function to preview the email and paste the image but I am unable to achieve the same in google app scripting. The image is different every time an email is sent and saving the image to a drive location defeats the automation effort so the preferred option is to paste the image before its sent. I would appreciate any suggestions and recommendations to make this happen. I am sure there is a way to do this and I am at the right place to find that way.
function SendNote() {
var active_range = SpreadsheetApp.getActiveSpreadsheet().getActiveRange();
var env_type = SpreadsheetApp.getActiveSheet().getRange(active_range.getRowIndex(), 1).getValue();
var count = SpreadsheetApp.getActiveSheet().getRange(active_range.getRowIndex(), 4).getValue();
var mail_type = SpreadsheetApp.getActiveSheet().getRange(active_range.getRowIndex(), 13).getValue();
// Check totals sales
if (mail_type = 'Kick_Off')
{
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
var emailAddress = emailRange.getValues();
// Send Email.
var message = 'This is my message ' + env_type; // Second column
var subject = 'This is the subject';
MailApp.sendEmail('myhandle#mymail.com', subject, message);
}
}

Related

Can I send multiple uploaded attachments from a Google Form/Google Sheet in an automated email?

I am trying to create a Google Form linked to a Google Sheet utilizing some Google App script that will take some answers from a survey, attach an uploaded file, and send an email to a specific person. I have been able to figure out the part where I collect the data in a Google Sheet and send an email, but the part where I take the uploaded file and have it as an attachment in the email is stumping me.
Currently, my code to send the email looks like this:
GmailApp.sendEmail(Recipient,subject,'',{htmlBody: htmlText},);
But looking at the documentation on sendEmail, it looks like I want to add more to that Options part, right? The so if I am defining a variable for this, I need to use getFileById, but the file ID will be different with each upload. Furthermore, I might need to attach multiple files.
I have created a test Google Form here and I have attached it to a Google Sheet here. You can see the Google App Script here. You can check the email being sent/received successfully by looking at formtesting4#mailinator.com as specified in the code.
Is that possible with what I am trying to do?
You can refer to this sample script:
function emailMe() {
const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const info = ss.getDataRange().getValues();
info.forEach((entry,a) => {
// Identify whether notification has been sent
if (entry[4] === '') {
// Collect entries
var Recipient = "your#email.com"
var subject = 'Roster Scheduler Update';
Timestamp = entry[0];
Name = entry[1];
Roster = entry[2];
attachment = "TEST";
var attachmentBlobs = [];
//Get the blob of all attachments available
if(entry[3]){
var attachments = entry[3].split(', ');
attachments.forEach(url => {
var fileId = url.replace('https://drive.google.com/open?id=','');
Logger.log(fileId);
var file = DriveApp.getFileById(fileId);
attachmentBlobs.push(file.getBlob());
});
}
let body = '';
// Generate email
var html = HtmlService.createTemplateFromFile("email.html");
var htmlText = html.evaluate().getContent();
// Send email
GmailApp.sendEmail(Recipient, subject, body, {htmlBody: htmlText, attachments: attachmentBlobs});
// Email confidence
const check = 'Sent';
ss.getRange(a + 1,5).setValue(check);
}
});
}
Changes done:
Get the blob file of all the uploaded attachments using File.getBlob(). You can get the file id from the attachment's url link and use DriveApp.getFileById(id)
Include body in the GmailApp.sendEmail() to fix email content issue
Include attachments as an option in the GmailApp.sendEmail(recipient, subject, body, options)
Output:
Sample1: 3 attachments
Sample2: 1 attachment

Google Docs script editor trying to autogenerate an email from an autogenerated document

Everything I've found about this topic includes having a google sheet populate a google doc which then sends an email. I personally have pasted some code I found around the web into script editor of a doc. Now, upon opening a doc, the user is prompted to answer question boxes. the answers autopopulate a new document that is created. The script then calls for an email to be sent out.
So far, I have the prompts correct, the new document is created, with the correctly filled-in information from the prompt boxes. I have also gotten it to send an email to 1 address, which is all it is supposed to do. The subject line of the email is also correct. The problem is I want the new Google document that is created in the script to be the body of the email, and I just cannot figure out how to make that happen.
This is the code I have in script editor. I have tried numerous things in the last line to make the body of the new document populate the email body, with no luck. Can someone tell me the programming language for how to make this work please?
function myFunction() {
// Display a dialog box for each field you need information for.
var ui = DocumentApp.getUi();
//var response = ui.prompt('Enter Name', 'Enter sales person's name', ui.ButtonSet.OK);
var shiftResponse = ui.prompt('Enter shift, i.e. 7-3 or 3-11');
var peersResponse = ui.prompt('Enter peers on shift');
var participantsResponse = ui.prompt('Enter names of face to face encounters');
var phonelogResponse = ui.prompt('Enter names of people we called on phone log');
var filescreatedResponse = ui.prompt('Enter names of people we created files for');
var notesResponse = ui.prompt('Enter any notes about shift');
var cleanResponse = ui.prompt('Was Crisis Center Cleaned? Enter yes or no');
var authorResponse = ui.prompt('Enter your name');
var date = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy");
//Make a copy of the template file
var documentId = DriveApp.getFileById('1lXTJPvwlJrXkRJ807daFsFbfaiC_wl7EAQ4giixLeEc').makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName(date + " " + shiftResponse.getResponseText() + ' Shift Report');
//Get the document body as a variable
var body = DocumentApp.openById(documentId).getBody();
//Insert the entries into the document
body.replaceText('##date##', date);
body.replaceText('##shift##', shiftResponse.getResponseText());
body.replaceText('##peers##', peersResponse.getResponseText());
body.replaceText('##participants##', participantsResponse.getResponseText());
body.replaceText('##phonelog##', phonelogResponse.getResponseText());
body.replaceText('##filescreated##', filescreatedResponse.getResponseText());
body.replaceText('##notes##', notesResponse.getResponseText());
body.replaceText('##clean##', cleanResponse.getResponseText());
body.replaceText('##author##', authorResponse.getResponseText());
MailApp.sendEmail("jason.chrystal#voicesofhopececilmd.org", "Shift Report", body);
}
As it reads in the documentation:
The replaceText methods expects a regex pattern value as the first parameter:
https://developers.google.com/apps-script/reference/document/body#replacetextsearchpattern,-replacement
Also the last parameter of the MailApp.sendMail parameter expects a string and you are giving it a body class object.
Change your first parameter to a correct matching regex pattern and your code will work just fine.
body.replaceText(/^##date##$/, date);
body.replaceText(/^##shift##$/, shiftResponse.getResponseText());
body.replaceText(/^##peers##$/, peersResponse.getResponseText());
etc...
-- regex not tested.
If you are not comfortable with regular expressions you can use body.setText() as an alternative like so:
var oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##date##', date));
oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##shift##', shiftResponse.getResponseText()));
oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##peers##', peersResponse.getResponseText()));
etc...
// And then the last lines:
var newBody = body.getText();
MailApp.sendEmail("jason.chrystal#voicesofhopececilmd.org", "Shift Report", newBody);

How can I send url of my Spreadsheet in email

How can I send url of my Spreadsheet by email ?
My code :
var emailAddress = "my email";
var url = "";
var subject = nom1;
MailApp.sendEmail(emailAddress, subject,url);
This code which send an email works.
But how can i get my url(speadsheet) ?
Assuming you already have your spreadsheet created, do the following steps:
Open your spreadsheet in google drive
Go to File->Share, a dialog should pop up with your share settings
At the top there should be a URL that you can send to people.
Some additional Notes:
If your spread sheet is set to private, you can change the settings such that only people who have the link are able to view the spreadsheet.
EDIT:
There is also getURL() in the apps script api
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getUrl()
var ss = SpreadsheetApp.getActiveSpreadsheet();
Logger.log(ss.getUrl());
So in your case:
MailApp.sendEmail(emailAddress, subject,ss.getUrl());

Sending Autoreponse Email Script on Form Submit

I've used a script in another spreadsheet that emails me whenever someone submits a form. It emails me with a few answers to important questions as well as a link to to view the full response on the spreadsheet.
Here is my original code that works:
function Outreach_FormMailer(e) {
var recipient = "email#gmail.com";
var timestamp = e.values[0];
var name = e.values[1];
var subject = e.values[1]+" completed a Report for "+e.values[3]
var dates = e.values[7];
var goalMet = e.values[9]
var goalFocus = e.values[10]
var hyperlink = "myawesomelink.com"
htmlBody = name+' just completed the O/R Report for these dates: '+dates+'<br><br>Form completed on: '+timestamp+'<br>Was the goal met? '+goalMet+'<br>What was the goal focus? '+goalFocus+
'<br><br>View the Form:Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}
I wanted to use this code for a new form with different questions, so I edited the code to just correspond to the correct qeustions.
This is the code that doesn't work:
function Team_ApplicationMailer(e) {
var recipient = "email#gmail.com";
var timestamp = e.values[0];
var name = e.values[3];
var subject = e.values[1]+' filled out the Teams Application Form!' ;
var startdate = e.values[12];
var enddate = e.values[13]
var Focus = e.values[19]
var hyperlink="myawesomelink.com"
htmlBody = name+' from: '+e.values[1]+'just completed the Teams Application Form for these dates: '+startdate+' to '+enddate+'<br><br>Form completed on: '+timestamp+'<br><br>View the Form:Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}
I've done several test emails and for some reason, this version of the script will not work. I am adding this script to a form that already has responses on the spreadsheet. Would that make a difference? Really not sure what I did wrong in transferring the code to a different spreadsheet.
Thanks for the comments guys. I actually realized the above code does work as is. I forgot that I setup a filter in Gmail that was sending the autoresponse email to a folder I didn't see instead of the inbox. No problem with the code, I just forgot to check the right place the email was sent to.

Google Forms Complex Email Send on Form Submit with Script

I have this right now as a script to send an email to myself as a test showing that there is a new application submitted, but I am looking to have a full-fledged email sent to our HR department giving the name of every field following by a : and a space then what their answer was. I know you can do this and have found a script that I tried to get to work, but it kept failing and the developer was no help in trying to help me fix it. I really would love to get this done for my HR department so that we can move on from creating a new application. Here is my code so far, I removed my email for privacy issues:
function sendFormByEmail(e){
var email = "emailgoeshere";
var subject = "A New Employment Application has been Submitted";
var message = "A New Application Has Been Submited. Please go to the spreadsheet for more details.";
MailApp.sendEmail(email, subject, message);
}
Thanks again!
Or you could try this very simple one :(read carefully comments in the script)
function sendFormByEmail(){
var email = "email adress comes here";
var subject = "A New Employment Application has been Submitted";
var message = "A New Application Has Been Submited. Please find the details below :";
var row = SpreadsheetApp.getActiveSpreadsheet().getLastRow();// assuming data is on the last row of the spreadsheet
var messagebody=createmessage(row);
MailApp.sendEmail(email, subject, message+messagebody);
}
//
function createmessage(row){
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lastCol = ss.getLastColumn();
var LF= "\r\n"
var body = LF
var headers = sh.getRange(1,1,1,lastCol).getValues();
var data = sh.getRange(row,1,1,lastCol).getValues();
for(nn=0;nn<headers[0].length;++nn){
body+=headers[0][nn]+" : "+data[0][nn]+LF
}
Logger.log(body)
return body
}
//
//eof
As mentionned, data coming from the form must be on last row of data in the sheet and there must be some data to check how it works otherwhise answers=questions.
I've developed a script that might help you, it's called FormEmailer. You can find it in the Script Gallery or grab the code on its site.