Send email with picture attachment and body using google script - google-apps-script

Hi im having trouble in sending email with image attachment. because the image file name is randomized and have no way to find out if the body of my message fits the image it will send from my drive. Here is a step by step of the process i have done:
online form integration to google spreadsheet (done)
online form to google drive (done) (images from each row of spreadsheet are saved by folder with folder name contains a unique id that is also present in the spreadsheet cell of each row)
What i would like to do here is get the images of folder in google drive by a.(searching the folder name which contains a ceratin text)
b.(getting the folder contents.)(all are images)
c.(attaching the contents of the folder to the email .)
Example:
function send() {
var picture1 = DriveApp.getFilesByName('snottyboy.jpg');
var picture2 = DriveApp.getFilesByName('daryl.jpg');
var recipientsTO = "fgh#gmail.com" + "," + "sdd#gmail.com"+ "," + "spaz#gmail.com"+ "," + "def#gmail.com"+ "," + "abc#gmail.com";
MailApp.sendEmail({
to:recipientsTO,
subject: "LOOK A LIKE",
body:"Final Message",
attachments: [picture1.next(),picture2.next()]
});
}
Thank you for your help.
See image:

To attach a file, you use File.getBlob() to attach it as a blob. For example:
attachments: [picture1.next().getBlob(),picture2.next().getBlob()]
If you know the exact id of a file (e.g. '0BxDqyd_bUCmvN1E3N0dQOWgycEF'), you can get it as a blob like this:
var picture3Blob = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycEF').getBlob();
Here's a working example:
function sendPics() {
var picture1 = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycFE'); //public with link
var picture2 = DriveApp.getFileById('0BxDqyd_bUCmvTFNjRkRXbXA2Tms'); //public with link
MailApp.sendEmail({
to: 'testa#example.com, testb#example.com',
subject: "This is a test",
body:"Test message",
attachments: [picture1.getBlob(), picture2.getBlob()]
});
}
and here's an example of the pictures being added inline instead of as attachments:
function sendPicsInline() {
var picture1 = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycFE'); //public with link
var picture2 = DriveApp.getFileById('0BxDqyd_bUCmvTFNjRkRXbXA2Tms'); //public with link
var inlineImages = {};
inlineImages[picture1.getId()] = picture1.getBlob();
inlineImages[picture2.getId()] = picture2.getBlob();
MailApp.sendEmail({
to: 'testa#example.com, testb#example.com',
subject: "This is a test",
body:"Test message",
htmlBody: 'Test message with pics inline <br>' +
'first:<br><img src="cid:' + picture1.getId() + '" /><br>' +
'second:<br><img src="cid:' + picture2.getId() + '" />',
inlineImages: inlineImages
});
}

Related

Auto-Generate PDF with Image (actual image, not link) and Data Input in Google Form

I'm creating a google form one can fill out to auto-generate a Digital Millennium Copyright Act notice as a PDF. The notice requires the original image in question to be included, so the form includes an upload file question. I want the generated PDF to include the actual image that was uploaded in the form, but right now all I get is the google drive link to the file's location.
How can I get the actual image to appear in the PDF? I'm attaching a screenshot of the Google Form, email output, and PDF template (marked with where the image should go) for reference.
Here's the script I have on the Google Sheet that's populated by the Google Form submissions:
function onSubmit(e) {
const rg = e.range;
console.log(rg.getA1Notation());
const sh = rg.getSheet();
//Get all the form submitted data
//Note: This data is dependent on the headers. If headers, are changed update these as well.
const Email= e.namedValues['Email Address'][0];
const LinkOrig = e.namedValues['Link(s) for where the original work appears'][0];
const AttachOrig = e.namedValues['Copies of the original copyrighted work'][0];
const Domain = e.namedValues['Infringing Domain'][0];
const LinkInfring = e.namedValues['Link(s) for where infringing image appears online'][0];
const Contact = e.namedValues['Contact Information'][0];
const WHOIS = e.namedValues['WHOIS Search results'][0];
const Date = e.namedValues['Date'][0];
const Location = e.namedValues['Where are you based?'][0];
//Build a new DMCA Form from the template
//Folder ID (save destination) and file IDs (template ID + new doc ID)
const DMCAFolderID = 'folderidhere';
const DMCALibFolder = DriveApp.getFolderById(DMCAFolderID);
const TemplateFileID = 'templateidhere';
const newFilename = 'DMCA Notice -' + TemplateFileID + 'Domain';
//Make a copy of the template file
const newTemplateFileID = DriveApp.getFileById(TemplateFileID).makeCopy(newFilename, DMCALibFolder).getId();;
//Get the DMCA Notice body into a variable
var document = DocumentApp.openById(newTemplateFileID);
var body = document.getBody();
//Replace all the {{ }} text in the template body
body.replaceText('{{LinkOrig}}', LinkOrig);
body.replaceText('{{AttachOrig}}', AttachOrig);
body.replaceText('{{LinkInfring}}', LinkInfring);
body.replaceText('{{ContactInfo}}', Contact);
body.replaceText('{{WHOISResults}}', WHOIS);
body.replaceText('{{date}}', Date);
body.replaceText('{{location}}', Location);
document.saveAndClose();
// define email variables
var subject = 'DMCA Notice - ' + Domain;
var msgHtml =
"Hi," + "<br/>" + "<br/>" +
"Please find your DMCA Notice attached." + "<br/>" + "<br/>" +
"Sincerely," + "<br/>" +
"Your Bada** Self" + "<br/>"
;
var attachment = DriveApp.getFileById(newTemplateFileID);
//send email with the file
GmailApp.sendEmail(Email, subject, msgHtml, {htmlBody: msgHtml, attachments: [attachment.getAs(MimeType.PDF)]});
}```
Assuming that {{AttachOrig}} is your placeholder and AttachOrig the URL of the file
You need to:
Obtain the image blob from the URL by opening it with DriveApp and getting the blob
Find the placeholder in your template
Replace the text by an empty string
Find the element that contains the placeholder
Get the element's parent paragraph
Insert the image blob into the parent paragraph
Sample:
var AttachOrig = "https://drive.google.com/file/d/1f8EFG6G5zNd6by_fNEecSh2D1My_p-_p/view";
function replacePlaceHolderThroughImage() {
...
var document = DocumentApp.openById(newTemplateFileID);
var body = document.getBody();
var placeholder = "{{AttachOrig}}";
var id = AttachOrig.match(/[\w\_\-]{25,}/)[0];
var img = DriveApp.getFileById(id);
var position = body.findText(placeholder);
var element = position.getElement();
element.asText().setText("");
element.getParent().asParagraph().insertInlineImage(0, img.getBlob());
}

Get file from Google Drive based of Google Form info submission

I have created a Google Form containing two fields (First Name, Last Name)
I have PDF files in Google Drive/specific folder, PDF files named as "First Name"+"Last Name"
I want to get PDF file from my Google Drive based on form submission and get the URL to be sent by email.
I need the way to get PDF file based on form user submission.
I have written the below code which shall send the PDF as email attachment in place of the URL of PDF. I hope this code can help you. This code is a very basic code which can be further advanced as per your needs. Please let me know if you need any further help.
function pdfextractor() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Get active spreadsheet.
var lastrow = ss.getLastRow();
var sheetName = ss.getRange("B" + lastrow).getValue() + " " + ss.getRange("C" + lastrow).getValue(); //considering format 'FirstName LastName' stored in column B & C of spreasheet generated by submission of google forms.
var pdfName = sheetName + ".pdf";
ss.getRange("D" + lastrow).setValue(pdfName);
var files = DriveApp.getFilesByName(pdfName);
var body = "This is a test email";
var subject = "PDF File "
var email = "admin#gmail.com"
while (files.hasNext()) {
var file = files.next();
}
GmailApp.sendEmail(email, subject, body, {
attachments: [file]
});
}
You can also change the email of each mail you want to send if stored with the sheet.
One way to do it is to create trigger that fires when the form is submitted. Based on this event, you can get the responses from the form submission, use them to search the file in Drive and send it attached to an email.
Here's an example that you can adapt to build what you need:
function onSubmit(e) {
// Get submitted responses
let itemResponses = e.response.getItemResponses();
// Get form answers (assume the form has three question in this order: First Name, Last Name, Email)
let firstName = itemResponses[0].getResponse();
let lastName = itemResponses[1].getResponse();
let email = itemResponses[2].getResponse();
// Get file (first file found with specified name)
let searchResult = DriveApp.searchFiles(`title contains \'${firstName+lastName}\'`);
let respondentFile = searchResult.next();
if (!respondentFile) throw 'File not found';
// Send email with respondent's file
MailApp.sendEmail(email, 'Your PDF File', 'Your PDF file is attached.', {
name: 'Automatic Emailer Script',
attachments: [respondentFile.getAs(MimeType.PDF)]
});
}

how to put inline image in automated mail from Google sheet

I want to send mail with an inline image instead of as an attachment through google sheet. Please help
the script is as below:
function emailSummary() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sh = ss.getSheetByName("Hitesh")
var file = DriveApp.getFileById('1T8QA_WsXQkZZGwmBSN13iPV7rM8xGG_GtYy6T1eug-c')
var gmail = 'hitesh.gtg#Gmail.com';
var html = '<png>'
MailApp.sendEmail("hitesh.gtg#gmail.com", "sunject", "Dear Sir,\n\n Forwarding herewith Monthly Summaryw \n\n Regards \n Hitesh ", {
//email address, subject, message
name: 'Hitesh', //file name
attachments: [file.getAs(MimeType.PDF)] //file to attach
});
}
You can pass HTML to the .sendMail() function. This link to the official documentation includes an example for inline images!
// This code fetches the Google and YouTube logos, inlines them in an email
// and sends the email
function inlineImage() {
var googleLogoUrl = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
var googleLogoBlob = UrlFetchApp
.fetch(googleLogoUrl)
.getBlob()
.setName("googleLogoBlob");
//You can also get these images from your drive to attach them.
var imgBlob = DriveApp.getFileById("<DRIVE_FILE_ID_OF_PICTURE>")
.getBlob()
.setName("imgBlob");
MailApp.sendEmail({
to: "recipient#example.com",
subject: "Logos",
htmlBody: "inline Google Logo<img src='cid:googleLogo'> images! <br>" +
"img from drive: <img src='cid:driveImg'>"
inlineImages:
{
googleLogo: googleLogoBlob,
driveImg: imgBlob
}
});
}
Emailing Images from your Google Drive
You can use the htmlBody parameter in GmailApp.sendMail(). However, if you want to avoid having to store the image in a URL that is publicly accessible. You can do something like this.
This is a portion of my JavaScript:
function sendImgMsg() {
var fileId=$('#mediaSel').val();//This is the fileId where the image is store. In my image converter script I keep all of this images in the same folder.
google.script.run
.withSuccessHandler(function(fObj){
var msg=$('#emsg').val();//This is the contents of a textarea
var hl='<p>' + msg + '</p><br /><strong>File Name:</strong> '+ fObj.name + '<img src="'+ fObj.uri +'" title="' + fObj.filetype + '" />';
$('#email').css('display','none');
google.script.run.sendImageMessage(hl);//This is the code that sends the email
})
.getSelectedFile(fileId);
}
This is a portion of my html:
<div id="email">
<textarea id="emsg" cols="40" rows="4"></textarea>
<br /><input type="button" value="Send" onClick="sendImgMsg()" />
</div>
This is a portion of my code.gs:
function getSelectedFile(fileId){
var file=DriveApp.getFileById(fileId);
var dataURI=file.getBlob().getDataAsString();
var s=dataURI.split(',')[0];
var mediaType=s.slice(s.indexOf(':')+1,s.indexOf('/'));
var fileType=s.slice(s.indexOf('/')+1,s.indexOf(';'));
var fObj={name:file.getName(),uri:dataURI ,type:mediaType,filetype:fileType};
return fObj;
}
function sendImageMessage(hl) {
GmailApp.sendEmail('recipient', 'ImageInAnEmail', null ,{htmlBody: hl});
}
This is the code that converts external images to imageURI's:
function convImageUrl(url){
var blob=UrlFetchApp.fetch(url).getBlob();
var b64Url='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
return b64Url;
}
The above is a part of a script that I use for converting images to imageURI's so that I can store and access them on my Google Drive.

Adding multiple attachments to email

I have a script which generates a document, saves as a PDF and attaches to an email. In addition to this attachment, I'm trying to add a second attachment which is an existing PDF saved on google drive (terms). Why is the following code not attaching the second document?
if (email_status == "YES" ) {
//send a pdf copy to customer
var pdfEMAIL = DriveApp.getFileById(doc.getId()).getAs('application/pdf').getBytes();
var terms = DriveApp.getFileById('file ID');
var message = "Hi " + usernamefordoctitle + "!, please kindly find your invoice attached.\nMany Thanks!\nMe";
var emailAdd = sheet.getRange("D2").getValue()
var emailTo = emailAdd; // add customer email here
var subject = "Invoice for " + usernamefordoctitle + " from ME" + " - Invoice Number : " + newInvNumber;
var attach = {fileName:"INVOICE " + newInvNumber + " " + usernamefordoctitle + '.pdf',content:pdfEMAIL, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach, terms.next()]});
ss.toast("70%: emailed customer");
Utilities.sleep(sleepINT);
}
You have
terms = DriveApp.getFileById('file ID');
followed by
terms.next()
This is incorrect, because getFileById gets you one specific file with the given Id. You were thinking of other methods like getFilesByName which return a file iterator. The name of the method is a clue to what it returns: getFile versus getFiles.
So, simply attaching
{attachments:[attach, terms]}
will work. You may also want to specify a MimeType like
terms.getAs(MimeType.PDF)
so that, e.g., you send a Google Doc as a PDF.

Send e-mail with InlineImages

I've created a script to send emails to a list of e.mail addresses with a PDF attachment. Now I want to "pimp it", adding a picture taken from Drive at the beginning of the email.
I found this method on Google Developers - sendEmail(recipient, subject, body, options) - but it's not crystal clear to me on how it works.
This is the code I wrote so far, but it's not working. I keep reading only the text, without any picture. It should take the first 50 rows of a spreadsheet, send an email to the address in column 9 and update column 11 once done.
var sheet = SpreadsheetApp.setActiveSheet(source.getSheets()[2]);
var row = 3
var subject = "Subject";
var imageId = DriveApp.getFileById("0B-OVYDHfkqhXOTF6aWVSSUtSbUE");
var htmlText = "<img src = "cid:imageId" /> Dear Friend, <BR> <BR> Text";
for (var i = 0; i <= 50; i++) {
var emailAddress = sheet.getRange(row + i, 9).getValue()
var message = "Hi,\n \n" + "text";
MailApp.sendEmail(emailAddress, subject, message, {
name: "Alternative Name",
htmlbody: htmlText,
attachments: [budgetPDF],
inLineImages: imageId
})
sheet.getRange(row + i, 11).setValue("Sent");
Could you please tell me what I'm doing wrong?
Thanks for your help!
You don't get the blob of the file.
var imageId = DriveApp.getFileById("0B-OVYDHfkqhXOTF6aWVSSUtSbUE");
var imageIdBlob = imageId.getBlob();
var htmlText = "<img src = 'cid:imageIdBlob' /> Dear Friend, <BR> <BR> Text";
.....
.....
MailApp.sendEmail(emailAddress, subject, message, {
name: "Alternative Name",
htmlbody: htmlText,
attachments: [budgetPDF],
inLineImages: imageIdBlob
})
As I don't know the format of the file you can also use getAs().
Stéphane