I'm trying to send an email with inline images to a series of users with myself in cc (myself#hotmail.com). I am trying to do this with the code written bellow. Everything seemed to work, but as soon as I added cc: 'myself#hotmail.com' it broke. My email gets send to the recipient 1x, but also to 'myself#hotmail.com' 8x. I cannot figure out what I am doing wrong, any help is much appreciated.
function sendEmails() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Emails").activate(); //makes sure your google sheets has the correct sheet open where you specify the emails and names
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); //defines spreadsheet to use
var lr = ss.getLastRow(); //gets last row on which there is data
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Template').getRange(1, 1).getValue() //gets email body from sheet 'template' which is defined in cell 1,1 -- make sure your sheet has same name else it won't work
var quotaLeft = MailApp.getRemainingDailyQuota(); //gets number of emails that you can still send
// Image URLs
var img1Url = "https://i.imgur.com/PRIVATE.png"; //CHANGE PRIVATE TAG
var img2Url = "https://i.imgur.com/PRIVATE.png"; //CHANGE PRIVATE TAG
// Fetch images as blobs, set names for attachments
var img1Blob = UrlFetchApp
.fetch(img1Url)
.getBlob()
.setName("img1Blob");
var img2Blob = UrlFetchApp
.fetch(img2Url)
.getBlob()
.setName("img2Blob");
//embeded image tags for email
var bodyImg1 = "<img src='cid:img1' style='width:1000px; height:1500px;'/>"; //specify img size here
var bodyImg2 = "<img src='cid:img2' style='width:1000px; height:1500px;'/>"; //specify img size here
if((lr-1) > quotaLeft){
Browser.msgBox("You have " + quotaLeft + " left and you're trying to send " + (lr-1) + " emails. Emails were not send"); //gives standard warning message if number of emails to be send exceeds limit
} else {
for (var i = 2; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue(); //gets email in excel sheet
var currentName = ss.getRange(i, 2).getValue(); //gets name in excel sheet
var subjectLine = "Invitation"; //title of email
var messageBody = templateText.replace("{name}", currentName); //replaces name in template with name of current cell, see templateText var
MailApp.sendEmail(currentEmail, subjectLine, subjectLine, {htmlBody: messageBody + bodyImg1 + bodyImg2, inlineImages:{img1: img1Blob,img2: img2Blob}, cc: 'myself#hotmail.com'});
} //close for loop
} //close else statement
} //close function
Solution:
MailApp.sendEmail({ to: currentEmail, subject: subjectLine, cc: 'myself#hotmail.com', htmlBody: messageBody + bodyImg1 + bodyImg2, inlineImages:{img1: img1Blob,img2: img2Blob}});
Related
I am currently using google script to submit a google form that is then auto-populates to google doc, the document then is emailed to the recipient. I have the main structure working, but I am experiencing couple of issues, noted below:
Error 'Script function not found: atosGoogleDocForm' once the form has been submitted, I cannot understand what I am doing something wrong, but the document still get's populated and saved.
When the email has been sent, the email isn't coming from the sender of who's completed the google form, but the email is received from the email that had sent the form/created the google form (not the form filler). I don't know what I am missing here.
I would really appreciate your help.
const googleDocTemplete = DriveApp.getFileById('1-MLB3MSn0-hb11vGkRM29KEiHpAeJFybhsTGYnytSRA');
const destinationFolder = DriveApp.getFolderById('1Kdbi08wkL3gH1y8c8ghp34E8vxpaj6qQ');
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form responses');
const rows = sheet.getDataRange().getValues();
function atosGoogleDocForm(e) {
var timestamp = e.values[0];
var email = e.values[1];
var name = e.values[5];
var access_date = e.values[10];
var access_time = e.values[11];
var business_reason = e.values[12];
rows.forEach(function(row, index) {
if (index === 0) return;
if (row[15]) return;
const copy = googleDocTemplete.makeCopy(`${row[5]} Atos Form`, destinationFolder);
const doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{Full Name}}", row[5]);
body.replaceText("{{Organisation}}", row[3]);
body.replaceText("{{DAS ID}}", row[4]);
body.replaceText("{{Emp Status}}", row[2]);
body.replaceText("{{Contact Address}}", row[6]);
body.replaceText("{{Contact Tel}}", row[7]);
body.replaceText("{{Atos Sponsor}}", row[8]);
body.replaceText("{{Sponsor DAS ID}}", row[9]);
body.replaceText("{{Access Date}}", access_date);
body.replaceText("{{Access Reason}}", business_reason);
body.replaceText("{{Access Time}}", access_time);
body.replaceText("{{timestamp}}", timestamp);
doc.saveAndClose();
const url = doc.getUrl();
sheet.getRange(index + 1, 16).setValue(url);
var recipient = "var5an1#hotmail.com";
var subject = name + " Atos PKI Form"
const html = '<p>Dear Reception, <br><br> Please find attached the application form for the ATOS PKI Card for ' + name + ' who will be attending to access the building on ' + access_date + ' at ' + access_time + '.' + "<br><br>Please let me know if you're experiencing any issues opening the file. The applicant will be collecting the PKI Card at Reception. <br><br>Kind regards<br><br></p>" + name + '<br><br><br>';
MailApp.sendEmail({
//from: email,
replyTo: email,
to: recipient,
cc: email,
subject: subject,
htmlBody: html,
attachments: [copy.getAs(MimeType.PDF)]
});
})
}
Can you please help me, How to send dynamic mail every latest entry in google sheet?
function CustomEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A2:C4");
var UserData = range.getValues();
for (i in UserData) {
var row = UserData[i];
var name = row[0];
var email = row[1];
var score = row[2];
MailApp.sendEmail(row[1], "Custom mail", "Hello " + name + ", This is an email report of your score. Your score is " + score);
}
}
Setup a trigger in your project: Trigger for "form submission". Whenever someone submits the form, script will send out the email to those whom the email wasn't sent. Also have a helper column in the sheet to update status for the script to filter out the people who already received the email, else others will keep receiving their scores everytime there's a form submission.
This is a script to send emails to the contacts I saved in googlespreadsheets. However, I want it only to send it to the last added email (not all the list). It keeps sending it to everyone included in the list and I want only to send to the last added email in row[2] where are the emails registered.
Thanks.
function sendEmail(e) {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var data = ws.getRange("A2:D" +ws.getLastRow()).getValues();
data.forEach(function(row) {
var html = HtmlService.createTemplateFromFile("htmlemail.html")
var htmlText = html.evaluate().getContent();
var subject = "Thanks for participation";
var textBody = "This email requires HTML support. Please make sure you open with a client that supports it.";
var options = { htmlBody : htmlText };
GmailApp.sendEmail(row[2], subject, textBody, options);
});
}
This will only email the last row every time.
function sendEmail(e) {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var data = ws.getRange(2,1,ws.getLastRow()-1,4).getValues();
var html = HtmlService.createTemplateFromFile("htmlemail.html")
var htmlText = html.evaluate().getContent();
var subject = "Thanks for participation";
var textBody = "This email requires HTML support. Please make sure you open with a client that supports it.";
var options = { htmlBody : htmlText };
GmailApp.sendEmail(data[data.length-1][2], subject, textBody, options);
}
if you do it this way then it will only use that line once unless you edit it with additional emails.
function sendEmail(e) {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
var data = ws.getRange(2,1,ws.getLastRow()-1,4).getValues();
var html = HtmlService.createTemplateFromFile("htmlemail.html")
var htmlText = html.evaluate().getContent();
var subject = "Thanks for participation";
var textBody = "This email requires HTML support. Please make sure you open with a client that supports it.";
var options = { htmlBody : htmlText };
if(data[data.length-1][2]) {
GmailApp.sendEmail(data[data.length-1][2], subject, textBody, options);
ws.getRange(data.length-1+2,3).setValue('');
}
}
I'm trying to add an image into the body of the emails. I've been able to get everything else working fine besides the image part. The images I'm trying to use are in the "M Column".
What do I need to add to get the value from the "M Column" and put it into the body of the emails?
-code is provided below
Thanks in advance. Everything I've tried has failed so I just removed everything I attempted and went to what I originally had before I decided to add images to the emails.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = 15;
var dataRange = sheet.getRange(startRow, 1, numRows, 15);
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[4];
var message = row[10];
var subject = "Subject Test";
MailApp.sendEmail(emailAddress, subject, message);
}
}
[error message][1]
[1]: https://i.stack.imgur.com/nwAJG.png
If you want to send an email which contains images, you could use one of the following options:
If your images are stored as urls in your Spreadsheet
The following code snippet is used to create the attachment containing the image gathered from a url stored in your Spreadsheet.
var imageUrl = sheet.getRange("YOUR_RANGE_FOR_THE_IMAGE").getValue();
var imageBody = "<img src='cid:myImage'>";
var imageBlob = UrlFetchApp.fetch(imageUrl)
.getBlob()
.setName("imageBlob");
var message = row[10];
var subject = "Subject Test";
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: message +"<br/><br/>"+ imageBody,
inlineImages:{
myImage: imageBlob
}
});
The above code snippet uses InlineImages in order to attach the image as an attachment into the email you want to send.
If your images are stored in drive and you have their file ids
The following code snippet is used to create the attachment containing the image gathered from the id of the file which is stored in Drive.
var imageId = sheet.getRange("YOUR_RANGE_FOR_THE_IMAGE").getValue();
var image = DriveApp.getFileById(imageId);
var imageBlob = Utilities.newBlob('', 'image/jpeg');
var message = row[10];
var subject = "Subject Test";
MailApp.sendEmail({
to: emailAddress,
subject: subject,
body: message,
attachments: [image.getAs(MimeType.JPEG), imageBlob]
});
If your images are stored inside a cell and/or as overgrid images
Unfortunately, Google Sheets doesn't have the capacity to return the blob of an image, only a reference to the image which means that you cannot retrieve the images and attach them afterwards in an e-mail using Google Apps Script.
In this case, an alternative would be to use the =IMAGE() function to insert the images in a cell and afterwards you can retrieve them by using the Sheets API V4.
Reference
MailApp Class Apps Script;
Sheets Class Apps Script getRange;
DrivApp Class Apps Script getFileById;
Apps Script Reference;
Sheets API.
Currently, my script is updating all cells within the selected range with "YES" but I only want it to update cells that meet the if conditions. Any help would be much appreciated.
//Active spreadsheet var that can be used anywhere in the programme
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get and check if there is an email address
function checkSendEmailAdd () {
//Getting the array of values
var activeSheet = ss.getActiveSheet();
var emailCol = activeSheet.getRange(2, 9, activeSheet.getLastRow() - 1, 2).getValues();
//Looping over the array of values
emailCol.forEach(function(val){
var email = val[0].toLowerCase();
var sentEmail = val[1];
//If the send date column is empty and the email column has a # within the string an email will be sent
if (email.indexOf("#") !== -1 && sentEmail == ""){
//Email contents
var subject = "Survey";
var body = "Hi" + "<br><br>" +
"Testing 123";
GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
//Update and set a new value in the sent email column
var newSetValue = "YES";
var updateSentEmail = activeSheet.getRange(2, 10, activeSheet.getLastRow() - 1, 1).setValue(newSetValue);
} else {
}
});
The problem I'm facing is that the sent column is updating every cell but I only want it to update the cells that have an email in the email column.
Image of what is being executed currently
Try it this way:
I tried to determine the columns from your question. I believe email was column one and sentMail was column two but if I'm wrong you can change them to whatever you need.
function sendEmail() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet0');
var vA=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
var sentA=sh.getRange(2,2,sh.getLastRow()-1,1).getValues();
var html='';
for(var i=0;i<vA.length;i++) {
var email=vA[i][0].toString().trim().toLowerCase();
var sentEmail=vA[i][1];
if(email && email.indexOf("#")>-1 && !sentEmail){
var subject = "Survey";
var body = "Hi<br><br>Testing 123";
//GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
html+=Utilities.formatString('<br />%s -<br />Email: %s<br />Subject: %s<br />Body: %s<br /><hr/>', Number(i+1),email,subject,body);
sentA[i][0]="Yes";
}
}
sh.getRange(2,2,sh.getLastRow()-1,1).setValues(sentA);
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Emails Sent');
}
Spreadsheet before sending:
Spreadsheet after sending:
I removed the Gmail line and used a dialog to display the emails: