I have a script that sends an email using GmailApp with an html body. I would like the html body to include specific values from the Spreadsheet that contains it, but each time the email is sent, the scriptlet I add is displayed as plain text.
email.gs:
function sendEmail() {
var mailTo = 'example#gmail.com'
var NAME = SpreadsheetApp.getActiveSheet().getRange('Sheet1!A1').getValue();
var subject = 'Hello!'
var html = HtmlService.createHtmlOutputFromFile('body').getContent();
GmailApp.sendEmail('', subject, '', {
name: 'Friend',
htmlBody: html,
bcc: mailTo
});
}
body.html:
<h1>Good Evening, <? NAME ?> </h1>
<h3>Hello Friend!</h3>
"NAME" should be pulled from the specified cell in the sheet whenever the script is run.
I am guessing that the reason it is displaying as text is GmailApp.sendEmail pastes the raw html into the email and assumes the client will read it, so how could I first get it to process through the script and then paste into the email?
Or you could use createTemplateFromFile and note "=" in
function sendEmail() {
var mailTo = 'example#gmail.com'
var subject = 'Hello!'
var html = HtmlService.createTemplateFromFile('body');
html.NAME = SpreadsheetApp.getActiveSheet().getRange('Sheet1!A1').getValue();
html = html.evaluate().getContent();
GmailApp.sendEmail('', subject, '', {
name: 'Friend',
htmlBody: html,
bcc: mailTo
});
}
<h1>Good Evening, <?= NAME ?> </h1>
<h3>Hello Friend!</h3>
You have the html body in a different file, and is not accessible by the NAME variable.
Try this.
function sendEmail() {
var mailTo = 'example#gmail.com'
var NAME = SpreadsheetApp.getActiveSheet().getRange('Sheet1!A1').getValue();
var bodyText = "<h1>Good Evening,"+ NAME +" </h1><br><h3>Hello Friend!</h3>"
var subject = 'Hello!'
GmailApp.sendEmail('', subject, '', {
name: 'Friend',
htmlBody: bodyText,
bcc: mailTo
});
}
Related
As you can see I am using this code to send an email to whoever submit the form.
However, I do get the error that var emailTo = e.namedValues[2].toString(); has the error of
"TypeError: Cannot read property 'namedValues' of undefined (line 5,
file "Code")"
function sendEmail(e) {
var html = HtmlService.createTemplateFromFile("htmlemail.html")
var htmlText = html.evaluate().getContent();
var emailTo = e.namedValues[2].toString(); //column B is for the email
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 (emailTo!== undefined){
GmailApp.sendEmail(emailTo, subject, textBody, options)
}
}
Please help. Note that column B in the spread sheet is where the email should be filled.
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.
So I have function like this which is called on button click:
function sendEmail() {
var subject = 'test subject';
var href = window.location.origin + window.location.pathname;
var body = 'test body: ' + href;
window.location.href = 'mailto:?subject=' + subject + '&body=' + body;
}
Is it possible to save this href in email body as a real link not as a string ??
Thanks for any suggestions.
No, it's impossible to implement like this because body should be plain text here.
You need to setup your mail function to send Content-Headers for TEXT/HTML instead of TEXT/PLAIN.
If so you can use simple html to send the mail.
That would make the link look like:
function sendEmail() {
var subject = 'test subject';
var href = window.location.origin + window.location.pathname;
var body = 'test body: Any Description';
}
If your solution would work it would be possible to force people to redirect to another page by reading their mails and for sure this should not be the case.
I want to send an email notification whenever the user clicks on a button. The button will call sendEmail(widget) function and invoke a client script as follow:
function sendEmail(widget){
var item = widget.datasource.item;
google.script.run
.withFailureHandler(function(error) {
console.text = error.message;
})
.withSuccessHandler(function(result) {
console.text = 'succeed';
})
.sendEmails(item);
}
then it will pass the datasource on item and call sendEmails(item) function from a server script as follows:
function sendEmails(item){
var to = item.OwnerEmail;
var subject = 'Please Review';
var body = 'hello<br/>my name is Muhammad Alif bin Azali';
MailApp.sendEmail({
to: to,
subject: subject,
htmlBody: body,
noReply: true
});
}
but when I click the button I got following error instead. Any help?
Unfortunately, you cannot pass whatever you want as a parameter to your server function. Communication to the server has some limitations:
...most types are legal, but not Date, Function, or DOM element...
...objects that create circular references will also fail...
App Maker's records definitely violate those restrictions.
There are different strategies to handle this limitation, one of them is passing record's key as function's parameter.
// Client script
function sendEmail(widget) {
var item = widget.datasource.item;
google.script.run
...
.sendEmails(item._key);
}
// Server script
function sendEmails(itemKey) {
var item = app.models.MyModel.getRecord(itemKey);
...
}
Looks like your Mail Body needs to be converted in HTML Body,
Here's the sample
function sendEmails(item){
var to = item.OwnerEmail;
var subject = 'Please Review';
var body = 'hello<br/>my name is Muhammad Alif bin Azali';
var template = HtmlService.createTemplate(body);
var htmlBody = template.evaluate().getContent();
MailApp.sendEmail({
to: to,
subject: subject,
htmlBody: htmlBody ,
noReply: true
});
}
I am new to NodeJS.
I started working on a contact us page, which, when submitted, sends out an acknowledgement email with following HTML to user.
<p>Hello Sujit,</p>
<p>Thank you for approaching us.</p>
<p>We have received your request and our executive will get in touch with you soon.</p>
<p>Thank you.</p>
Following is the code to send email:
var mailer = require("nodemailer");
var emailBody = "<HTML above>";
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport("SMTP",{
service: "#######",
auth: {
user: "#########",
pass: "#######"
}
});
var mail = {
from: "######################",
to: params.email,
subject: "Welcome user.",
text: "",
html: emailBody
}
smtpTransport.sendMail(mail, function(error, response){
if(error){
console.log("Mail error:>>");
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
smtpTransport.close();
});
Currently, using nodemailer, I am sending this email with the HTML body defined in the same file - app.js. It is working fine so far.
But, is there any way I can separate the HTML with variables/placeholders for "name" and place in some other file, so that the body content can be managed directly? Some way by which I can load the body content into the variable emailBody.
Thanks.
Yes!! Create one folder with name "templates" inside that create text files for particular email. Like welcome.txt. In welcome.txt write code like
<p>Hello #name,</p>
<p>Thank you for approaching us.</p>
Then using fs module you can read that file like fs.readFile([filepath]) and store this value in variable . Like var mailContent = fs.readFile([filepath]). Then using javascript replace function replace #name with actual name .
Like mailContent.replace('#name','abcd')
Yes, you can maintain a JSON structure with key value pair.
template.json
{
"Subject" : "Acknowledgement Mail",
"Body" : Above HTML
}
And then you can read require this JSON or pass this as a parameter to your function.
var template = require('./templates.json);
var mail = {
from: "######################",
to: params.email,
subject:template.Subject,
text: "",
html: template.Body
}