Send an email with Multipart (csv attachment and HTML) in MarkLogic - javascript

I would like to send an email with multipart using MarkLogic. Multipart contains csv attachment and HTML.I am able to attach CSV file but not able to show HTML content in multipart. In below code HTML content are being processed as an attachment without any data.
var boundary = "blahblahblah" + xdmp.random();
var contentType = "multipart/mixed; boundary=" + boundary;
var att1 = xdmp.base64Encode(exportToCsv());
var part1 = "Notification and Alert";
var htmlString = '<html> <body> <p> Tracking Details </p> </body> </html> '
var part2 = {
"Content-Type": "csv/text",
"Content-Disposition":"attachment",
"filename":"Notification "+queryDate+".csv",
"Content-Transfer-Encoding":"base64",
"attachment":att1
};
var part3 = {
"Content-Type": "text/html",
"Content-Disposition":"inline",
"Content":htmlString
};
var from = {"name":"Team", "address":"zzzz#zzz.com"};
var to = {"addresses":[mailId]};
var subject = "Tracking Update"+" "+queryDate;
var message = {
"from":from,
"to":to,
"subject": subject,
"content-type":contentType,
"content":{
"boundary":boundary,
"parts":[part1,part2,part3]
}
};

Related

Send an email with an HTML table, with attachment, when a Google Form response is submitted

I have a function that runs on an installable "on form submit" trigger. It sends an an email when a form response is submitted.
The Google Form has multiple questions including a question that lets the responder include attachments. I need to send both questions and answers in a table format. The questions should be in bolded in the table. The attachments should be included in the email.
Here's my current code:
function onFormSubmit() {
var email = "example#gmail.com";
var subject = "Form Responses";
var body = "<table>";
var attachments = [];
var form = FormApp.getActiveForm();
var responses = form.getResponses();
var lastResponse = responses[responses.length-1];
var itemResponses = lastResponse.getItemResponses();
for (var i = 0; i < itemResponses.length; i++) {
var question = itemResponses[i].getItem().getTitle();
var response = itemResponses[i].getResponse();
body += "<tr><td><b>" + question + "</b></td><td>" + response + "</td></tr>";
if (itemResponses[i].getItem().getType() === FormApp.ItemType.FILE_UPLOAD) {
var fileId = itemResponses[i].getResponse().getId();
var file = DriveApp.getFileById(fileId);
attachments.push(file.getBlob());
}
}
body += "</table>";
GmailApp.sendEmail(email, subject, "", {htmlBody: body, attachments: attachments});
}
The problem is that the code errors out:
TypeError: itemResponses[i].getResponse(...).getId is not a function.
How do I fix that?
itemResponses[i].getResponse() is a string not a file. Try this.
let fileId = DriveApp.getFilesByName(itemResponses[i].getResponse()).next().getId();
Although I would suggest you use try catch incase a file of that name doesn't exist.

Google Script - Export a document to PDF

I'm pretty new to programming and don't really know Javascript. Recently, to help out my mother with her business, I've came up with the script below.
Basically it takes information from a sheet (the sheet is filled with answers from Google Forms), copy a template document and then replace some fields in the copied document with those informations.
Now what I'm trying to do is to export the filled document to PDF, can someone help?
Here's the actual script:
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var timestamp = e.values[0];
//client info
var nome = e.values[1];
var cpf = e.values[2];
var rg = e.values[3];
var rua = e.values[4];
var numero = e.values[5];
var bairro = e.values[6];
var cidade = e.values[7];
var estado = e.values[8];
var cep = e.values[9];
var celular = e.values[10];
//seller info
var nome_vendedor = e.values[11];
var cpf_vendedor = e.values[12];
//template is the template file, and you get it by ID
var template = DriveApp.getFileById('1VB5u4OrqIQO8P6scj-rzkjtRlZ8NI-ZKd9xGKfnEqBA');
//acess main folder
var mainfolder = DriveApp.getFolderById('1G6g2VyrvpKpqSvLei3_jefQMNsGb-be0');
//create a new folder
var newFolderId = mainfolder.createFolder(nome + ' ' + cpf).getId();
//get new folder Id
var id = DriveApp.getFolderById(newFolderId);
//copy the template file to the new folder
var copy = template.makeCopy(nome + ' ' + cpf, id);
//open the document by it's Id
var document = DocumentApp.openById(copy.getId());
//get to the doc body for the replace
var body = document.getBody();
////////////
////////////
////////////
////////////
////////////
//ReplaceText methods
////////////
////////////
////////////
////////////
//client info
body.replaceText('{{nome}}', nome);
body.replaceText('{{cpf}}', cpf);
body.replaceText('{{rg}}', rg);
body.replaceText('{{rua}}', rua);
body.replaceText('{{numero}}', numero);
body.replaceText('{{bairro}}', bairro);
body.replaceText('{{cidade}}', cidade);
body.replaceText('{{estado}}', estado);
body.replaceText('{{cep}}', cep);
body.replaceText('{{celular}}', celular);
//seller info
body.replaceText('{{nome_vendedor}}', nome_vendedor);
body.replaceText('{{cpf_vendedor}}', cpf_vendedor);
//save and close the document
document.saveAndClose();
}
The easiest way to export a Goolge Document to pdf is using the UrlFetchApp
You need the
basic export url
the file id
specofy export parameters if and as required
An access token that you can obtain with the ScriptApp
Sample snippet based on you code before where you already have the document id:
var url = "https://docs.google.com/document/d/"+id+"/export?";
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+'&top_margin=0.50'
+'&bottom_margin=0.50'
+'&left_margin=0.50'
+'&right_margin=0.50'
// other parameters if you need
/*
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false' // hide page numbers
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
*/
var response = UrlFetchApp.fetch(url + url_ext,
{
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
muteHttpExceptions:true
});
DriveApp.createFile(response.getBlob().setName("myPdf"));

How to send image and charts using mailapp?

I'm trying to send an image and spreadsheet chart in an email together but I can only send one or the other. For example, i can only send images and the chart will not appear and if i send charts the images will not appear. I'm also new to this, thanks for the help.
{
function emailCharts(sheet,emails,emailSubject){
DriveApp.getRootFolder()
var targetspreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Active spreadsheet of the key file
var sheet = targetspreadsheet.getSheetByName('Test'); // Change the sheet name Eg.'IPQC Overall Tracker' to your sheet name
var emailSubject = 'Scratches Awareness Program Test';
var emails = 'example#gmail.com'; // your email ID
var charts = sheet.getCharts();
if(charts.length==0){
MailApp.sendEmail({
to: emails,
subject: "ERROR:"+emailSubject,
htmlBody: "No charts in the spreadsheet"});
return;
}
var emailStarting = "<br>########TEST##########<br>"
var emailEnding = "#################################<br>"
var emailSignature = "<br>Best Regards, <br>############<br><br> This is an automated generated email. No signature is required."
var chartBlobs=new Array(charts.length);
var emailBody="Hi Everyone,<br>" + emailStarting;
var emailImages={};
for(var i=0;i<charts.length;i++){
var builder = charts[i].modify();
builder.setOption('vAxis.format', '#');
var newchart = builder.build();
chartBlobs[i]= newchart.getAs('image/png');
emailBody= emailBody + "<p align='center'><img src='cid:chart"+i+"'></p>" ;
emailImages["chart"+i]= chartBlobs[i];
}
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
var requestData = {"method": "GET",
"headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl =
"https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp
.fetch(googleLogoUrl)
.getBlob()
.setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp
.fetch(youtubeLogoUrl)
.getBlob()
.setName("Scratches Dashboard");
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages:emailImages, attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}],googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob});
}
}
You want to send the images of charts, googleLogoBlob and youtubeLogoBlob as the inline images, and want to send Excel file (xlsx format) as the attachment file.
You want to achieve this using Google Apps Script.
I could understand like this. If my understanding is correct, how about this modification? Please think of this as just one of several answers.
Modification points:
format=xlsx is used for converting Google Spreadsheet to Excel.
{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"} is used as the attachment file.
Please modify to {fileName:sheetName+".xlsx", content:contents, mimeType: MimeType.MICROSOFT_EXCEL}.
googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob is directly used as the object for MailApp.sendEmail(object). And googleLogo and youtubeLogo are not included in the inline images.
Please include those image to the inline images.
When above points are reflected to your script, it becomes as follows.
Modified script:
Please modify your script as follows.
From:
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl =
"https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp
.fetch(googleLogoUrl)
.getBlob()
.setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp
.fetch(youtubeLogoUrl)
.getBlob()
.setName("Scratches Dashboard");
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages:emailImages, attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}],googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob});
}
}
To:
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx"; // Modified
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl = "https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp.fetch(googleLogoUrl).getBlob().setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp.fetch(youtubeLogoUrl).getBlob().setName("Scratches Dashboard");
emailBody += "<img src='cid:googleLogo'><img src='cid:youtubeLogo'>"; // Added
emailImages.googleLogo = googleLogoBlob; // Added
emailImages.youtubeLogo = youtubeLogoBlob; // Added
MailApp.sendEmail({ // Modified
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages: emailImages,
attachments: [{fileName: sheetName+".xlsx", content: contents, mimeType: MimeType.MICROSOFT_EXCEL}],
});
}
Note:
About googleLogo and youtubeLogo, please modify <img src='cid:googleLogo'><img src='cid:youtubeLogo'> for your actual situation.
References:
sendEmail(message)
Enum MimeType
Your code is fine, the only isssue you are having is the way you're building your MailApp.sendEmail() . Do it in this way:
var emails = "example#gmail.com";
var emailSubject = "Test Subject";
var body = emailBody + emailEnding + emailSignature;
var spreadsheetObj = {
fileName:sheetName+".xls",
content:contents,
mimeType:"application//xls"
};
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: body,
attachments: [ spreadsheetObj, googleLogoBlob, youtubeLogoBlob]
});
The attachments must be an array, you were building it in the wrong way. As the Docs says:
attachments BlobSource[] An array of files to send with the email (see example)
Notice:
If you attach several files, the email can take some time to be delivered.

how to load data using a javascript

I have almost zero experience with Javascript , I need to use this Javascript in my php script .
<script>
let arr = ["alfa", "beta", "charlie"]
const updateResult = query => {
let resultList = document.querySelector(".result");
resultList.innerHTML = "";
arr.map(algo =>{
query.split(" ").map(word =>{
if(algo.toLowerCase().indexOf(word.toLowerCase()) != -1){
resultList.innerHTML += `<li class="list-group-item">${algo}</li>`;
}
})
})
}
updateResult("")
</script>
This script load the data using
let arr =
However suppose I have all the data specified there in a file in this format
c:/data/mydata.txt
and the data.txt contains data in this form (one data per row)
alfa
bravo
charlie
Now how should I change the javascript above to load the data from c:/data/mydata.txt and not using
let arr = ["alfa", "beta", "charlie"]
?
Thank you
You do not need to change your file, but you cannot use it directly due to security issues. If I would write a Javascript which reads your secret files and you load my page, all your secrets would be revealed, therefore, if you want to load a file, you either have to allow your user to upload it and once the user uploads the file do your logic, or, you can request it via AJAX.
How to upload a file
An example for this is
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>
</body>
</html>
source: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
Getting the file via AJAX
In order to do that, you will need to:
send an AJAX request in your javascript code
parse the request and send back the file via PHP
do your logic in Javascript when the request is responded
Example:
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Download POST Request</title>
</head>
<body>
Enter a text and click the button: <input type="text" id="content" value="Text for the generated pdf">
<button id="download">Send AJAX Request and download file</button>
<script>
document.getElementById('download').addEventListener('click', function () {
var content = document.getElementById('content').value;
var request = new XMLHttpRequest();
request.open('POST', '../server/', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
// Only handle status code 200
if(request.status === 200) {
// Try to find out the filename from the content disposition `filename` value
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
// The actual download
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// some error handling should be done here...
};
request.send('content=' + content);
});
</script>
</body>
</html>
PHP
<?php
require_once 'vendor/autoload.php';
if($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-type: application/pdf');
http_response_code(200);
// Contents
$pdfContent = !empty($_POST['content']) ? $_POST['content'] : 'no content specified';
// Generate the PDOF
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10, $pdfContent);
return $pdf->Output(null, 'foobar-' . time() . '.pdf');
}
// Bad method
http_response_code(405);
exit();
Source: https://nehalist.io/downloading-files-from-post-requests/
You will of course need to modify the code to comply to your needs. Reading a tutorial would not hurt.
you can use ajax for loading data from external file.
a sample of jquery get call is given below. You can also use the same code with your file path and variables.
$("button").click(function(){
$.get("demo_test.php", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
if you are using pure java script instead of jQuery you have to use pure ajax calls.
for more details about jQuery ajax check this link

onFormSubmit trigger not working for sending out email upon form submission

I have a piece of code here which, on form submission, is supposed to:
Perform some calculations in a spreadsheet using the form responses, create a pdf file containing the user's results, and email this to them.
I have set up a trigger which runs "onFormSubmit", with events "From Spreadsheet", "onFormSubmit" and Here is my code:
//Set out global variables
var docTemplate = "1Ff3SfcXQyGeCe8-Y24l4EUMU7P9TsgREsAYO9W6RE2o";
var docName="Calculations";
//createOnFormSubmitTrigger();
function onFormSubmit(e){
//Variables
var ssID = '1dMmihZoJqfLoZs9e7YMoeUb_IobW4k6BbOuMDOTTLGk';
var ss = SpreadsheetApp.openById(ssID);
ss.setActiveSheet(ss.getSheetByName("Sheet3"));
var totalOutstandingPrincipalDebt = SpreadsheetApp.getActiveSheet().getRange("G25").getValue();
var totalOutstandingInterest = SpreadsheetApp.getActiveSheet().getRange("H25").getValue();
var totalOutstandingCompensation = SpreadsheetApp.getActiveSheet().getRange("I25").getValue();
var dailyInterestRate = SpreadsheetApp.getActiveSheet().getRange("J25").getValue();
var grandTotal = SpreadsheetApp.getActiveSheet().getRange("K25").getValue();
var userEmail = SpreadsheetApp.getActiveSheet().getRange("H24").getValue();
//Template Info
var copyId=DriveApp.getFileById(docTemplate).makeCopy(docName+' for '+userEmail).getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
//Putting the data into the file
copyBody.insertParagraph(1,'Total Outstanding Principal Debt: £' + totalOutstandingPrincipalDebt);
copyBody.insertParagraph(2,'Total Outstanding Interest: £'+ totalOutstandingInterest );
copyBody.insertParagraph(3,'Total Outstanding Compensation: £'+ totalOutstandingCompensation);
copyBody.insertParagraph(4,'Grand Total: £' + grandTotal);
copyBody.insertParagraph(5,'Daily Interest Rate: £'+ dailyInterestRate);
copyDoc.saveAndClose();
//email pdf document as attachment
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var subject = "Calculations";
var body = "Thank you very much for using our online calculator. Please find your results attached.";
MailApp.sendEmail(userEmail, subject, body, {htmlBody: body, attachments: pdf});
//Deletes temporary Document
DriveApp.getFileById(copyId).setTrashed(true);
}
The script will sometimes run fine when I am in the script editor (not always?!), but when I submit a form, I receive the following error notification: "Failed to send email: no recipient (line 40, file "Code")", where line 40 is the line:
MailApp.sendEmail(userEmail, subject, body, {htmlBody: body, attachments: pdf});
I have tried using getNote() instead of getValue() for the userEmail variable but that didn't work either! I have also made sure the cell reference on the spreadsheet is formatted as plain text rather than as a number, but I'm not sure what else to try now! Any suggestions would be greatly appreciated!
Thanks so much in advance :)
It's working now since I changed:
var ssID = '1dMmihZoJqfLoZs9e7Y.............';
var ss = SpreadsheetApp.openById(ssID);
ss.setActiveSheet(ss.getSheetByName("Sheet3"));
var totalOutstandingPrincipalDebt = SpreadsheetApp.getActiveSheet().getRange("G25").getValue();
var totalOutstandingInterest = SpreadsheetApp.getActiveSheet().getRange("H25").getValue();
var totalOutstandingCompensation = SpreadsheetApp.getActiveSheet().getRange("I25").getValue();
var dailyInterestRate = SpreadsheetApp.getActiveSheet().getRange("J25").getValue();
var grandTotal = SpreadsheetApp.getActiveSheet().getRange("K25").getValue();
var userEmail = SpreadsheetApp.getActiveSheet().getRange("H24").getValue();
to:
var ssID = '1dMmihZ.................';
var ss = SpreadsheetApp.openById(ssID);
var sheet = SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);
var totalOutstandingPrincipalDebt = sheet.getRange("G25").getValue();
var totalOutstandingInterest = sheet.getRange("H25").getValue();
var totalOutstandingCompensation = sheet.getRange("I25").getValue();
var dailyInterestRate = sheet.getRange("J25").getValue();
var grandTotal = sheet.getRange("K25").getValue();
var userEmail = sheet.getRange("H24").getValue();

Categories

Resources