Google App Script doesn't set Bcc adress - google-apps-script

I have develop a simple google app script to send an email with bcc I just trying to URL param To, From and subject is set is correctly but, the cc and bcc address are not set properly
My code snippet is here.
function doPost(e) { // change to doPost(e) if you are recieving POST data
var mailId = '';
var mailSubject = '';
var mailBody = '';
var htmlBody = '';
var senderName = '';
var replyToAddress = '';
var bccAddresses = '';
mailId = e.parameter['Email'];
mailSubject = e.parameter['Subject'];
mailBody = e.parameter['MailBody'];
htmlBody = e.parameter['HtmlBody'];
senderName = e.parameter['SenderName'];
replyToAddress = e.parameter['ReplyTo'];
bccAddresses = e.parameter['bccAddress'];
Logger.log(':::::::mailId:::::',mailId);
if(mailId != '' && mailId != null){
MailApp.sendEmail({
to:mailId,
subject:mailSubject,
htmlBody:mailBody,
bcc:bccAddresses,
name:senderName,
replyTo:replyToAddress,
});
}
var emailQuotaRemaining = MailApp.getRemainingDailyQuota();
return ContentService
.createTextOutput(emailQuotaRemaining);
}
function doGet(request) {
var emailQuotaRemaining = MailApp.getRemainingDailyQuota();
var result = {
available: 0
};
return ContentService.createTextOutput(
request.parameters.prefix + '(' + emailQuotaRemaining + ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
My HTML code is
<form method="post" style="display:none;" id="form" action="https://script.google.com/macros/s/AKfycbwlMz27gP9vxZA-X58wvxgerhG46A6TEZw33YFe5mvJ0ejFSYQt/exec">
<input type="text" name="Subject" value="Test Subject" />
<input type="text" name="MailBody" value="Test Body" />
<input type="text" name="Email" value="subashc#softsquare.biz" />
<input type="text" name="SenderName" value="MSCB" />
<input type="text" name="ReplyTo" value="test#gmail.com" />
<input type="text" name="bccAddress" value="mscb39#yahoo.com" />
<textarea name="HtmlBody">Test Body</textarea>
<input type="submit" id="sub" />
</form>
<button onclick="subForm();">Submit</button>
<script>
function subForm() {
document.getElementById('form').submit();
}
</script>
Thanks in Advance,
Subash Chandrabose.M

Could you put BCC in the options and test.
MailApp.sendEmail(to, subject, "", {
htmlBody:mailBody,
bcc:bccAddresses,
name:senderName,
replyTo:replyToAddress
});

It seems as though you aren't refrencing a bcc adress when you are calling your function.. How are you calling your function?
(I would comment but I don't have enough reputation yet)

Related

Can't login into a site using Google Apps Script and receive error 422

I need to scrape private data from a Japanese site.
But I can't login into the site and receive error code 422.
How can I login?
I need to log in into this website:
https://moneyforward.com/users/sign_in
The form on this site is:
<form class="form-horizontal mf-mb40" id="new_sign_in_session_service" action="/session" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓" />
<input type="hidden" name="authenticity_token" value="OGuijdFq6M1xngenCHi0BgZh9x0Nniw2HxiRhC9H2T0vbgWcWNRz+fmi5wxEdk4ua5TL9/UF7BapR2Af8CdILQ==" />
<div class="a-text--f14 mb3">e-mail</div><div class="a-text-box">
<input placeholder="entry" class="js-focus-form" type="email" name="sign_in_session_service[email]" id="sign_in_session_service_email" />
</div>
<div class="a-text--f14 mb3 mt20">password</div><div class="a-text-box">
<input placeholder="entry" type="password" name="sign_in_session_service[password]" id="sign_in_session_service_password" />
</div>
<div class="m-password-support">
<div class="a-checkbox password-show">
<label><input class="checkbox" id="show-ps" name="new1" type="checkbox" value="1" />
<span class="checkbox-icon"></span>
<span class="checkbox-txt">password</span></label>
</div>
<div class="password-forget">
forgot password
</div>
</div>
<div class="a-button primary">
<input type="submit" name="commit" value="login" id="login-btn-sumit" data-disable-with="login" />
</div>
</form>
I receive the error on last row "var response = UrlFetchApp.fetch(url, options)" below code.
function Login() {
var account ='***';
var password = '***';
var response = UrlFetchApp.fetch("https://moneyforward.com/users/sign_in");
var regexp = /<input type=\"hidden\" name=\"authenticity_token\" value=\"(.*?)\" \/>/;
var elements = response.getContentText().match(regexp);
var headers = response.getAllHeaders();
var cookies = [];
if ( typeof headers['Set-Cookie'] !== 'undefined' ) {
var cookies = typeof headers['Set-Cookie'] == 'string' ? [ headers['Set-Cookie'] ] : headers['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].split( ';' )[0];
};
};
var payload = {
utf8: "✓",
authenticity_token : elements[1],
email : "account",
password : password
};
var headers = { 'Cookie' : cookies };
options = {
method : "post",
headers : headers,
followRedirects: true,
contentType: "application/x-www-form-urlencoded",
//muteHttpExceptions : true,
payload : payload,
};
var url = "https://moneyforward.com/session";
var response = UrlFetchApp.fetch(url, options);
}

Saving information in google sheets from my form

I try to save file on google drive and information in google sheets. But information in Sheets comes like Java.object.
Here is how it looks like in Code.gs :
var FOLDER_ID = '1jxBwrsz0JdBHcADpUUMespe';
var SHEET_ID = '1oJcKQ2RrtxxE1mn_CP-UAHefDxV7zg4';
function doPost(e) {
var data = Utilities.base64Decode(e.parameters.data);
var blob = Utilities.newBlob(data, e.parameters.mimetype, e.parameters.name);
var folder = DriveApp.getFolderById(FOLDER_ID);
var file = folder.createFile(blob);
folder.createFolder(name)
var res = [];
SpreadsheetApp.openById(SHEET_ID).getSheets()[0].appendRow([e.parameters.name, file.getUrl()].concat(res));
return ContentService.createTextOutput("Done.")
}
Here is how it looks like in the HTML file :
<form action="https://script.google.com/macros/s/AKfycbxkzg6ud1VyTI2W4gs-CRJRS3i3qLDXQIGevtyy/exec" id="form" method="post">
<div id="data"></div>
<div class="form-group">
<label for="name">Имя</label>
<input type="text" id='name' name="name" placeholder="Имя" />
</div>
<div class="form-group">
<label for="comment">Комм</label>
<input type="text" name="comment" placeholder="Комментарий" />
</div>
<input name="file" id="uploadfile" type="file">
<input id="submit" type="submit">
</form>
<script>
$('#uploadfile').on("change", function() {
var file = this.files[0];
var fr = new FileReader();
var name = $('#name').value;
fr.fileName = file.name
fr.onload = function(e) {
e.target.result
html = '<input type="hidden" name="data" value="' + e.target.result.replace(/^.*,/, '') + '" >';
html += '<input type="hidden" name="mimetype" value="' + e.target.result.match(/^.*(?=;)/)[0] + '" >';
html += '<input type="hidden" name="filename" value="' + e.target.fileName + '" >';
html += '<input type="hidden" name="name" value="' + name + '" >';
$("#data").empty().append(html);
}
fr.readAsDataURL(file);
});
</script>
Result in Google sheet
How to get data in a readable format?
Personally, I never use forms. Here's an examples that creates 5 text boxes. Validates that you put something into them and returns the code to the server via google.script.run for further processing (i.e. Logger.log the data). I create the html server side and loaded it on the on DOM ready event with JQuery.
Codes.gs
function buildForm(){
var s='';
for(var i=0;i<5;i++){
s+=Utilities.formatString('<br /><input class="jim" type="text" value="" id="%s" />%s',"txt" + i,"text" + Number(i+1));
}
s+='<br /><input type="button" value="Submit" onClick="getValues();" /><input type="button" value="Close" onClick="google.script.host.close();" />';
return s;
}
function saveValues(A){
for(var i=0;i<A.length;i++){
Logger.log('\nid=%s\nvalue=%s',A[i].id,A[i].value);
}
}
function showFormDialog(){
var ui=HtmlService.createHtmlOutputFromFile('form')
SpreadsheetApp.getUi().showModelessDialog(ui,'My Form');
}
form.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(html){$('#form').html(html);})
.buildForm();
});
function getValues(){
var elements=document.getElementsByClassName('jim');
var el=[];
console.log('elements.length=%s',elements.length);
for(var i=0;i<elements.length;i++){
var obj={};
obj['id']='txt' + i;
obj['value']=$('#' + 'txt' + i).val();
el.push(obj);
}
var dataValid=true;
for(var i=0;i<el.length;i++){
console.log('id=%s, value=%s',el[i].id, el[i].value);
if(!el[i].value){
dataValid=false;
$('#'+el[i].id).css('background','#ffff00');
}else{
$('#'+el[i].id).css('background','#ffffff');
}
}
if(dataValid){
google.script.run.saveValues(el);
}else{
alert('Invalid Data Found...Try again sucker....');
}
}
console.log('MyCode');
</script>
<style>
input {margin:5px 5px 0 0;}
</style>
</head>
<body>
<div id="form"></div>
</body>
</html>

Google Scripts HtmlService returns undefined form data

I am trying to create a web app whereby a user fills out a form and the data gets populated into a google sheet. My problem is after I fill out the form the sheet gets populated with undefined data.
How do I define this data and append to a new row each time I fill out the form.
Example was taken from here.
Code.gs
function doGet(e){
return handleResponse(e);
}
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return HtmlService.createHtmlOutputFromFile('index');
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
var $form = $('form#test'),
url = 'https://...';
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(
// do something
);
})
</script>
</head>
<body>
<form id="test">
<p><label>ID</label>
<input type="number" name="ID"/></p>
<p><label>Part Number</label>
<input type="text" name="Part Number"/></p>
<p><label>Description</label>
<input type="text" name="Description"/></p>
<p><label>Item Link</label>
<input type="url" name="Item Link"/></p>
<p><label>Supplier</label>
<input type="text" name="Supplier"/></p>
<p><label>Manufacturer</label>
<input type="text" name="Manufacturer"/></p>
<p><label>Pins</label>
<input type="number" name="Pins"/></p>
<p><label>Size</label>
<input type="text" name="Size"/></p>
<p><label>Order Number</label>
<input type="number" name="Order Number"/></p>
<p><label>Location</label>
<input type="text" name="Location"/></p>
<p><input type="submit" value="submit-form"/></p>
</form>
</body>
</html>
Since you've borrowed code from another site it seems overly complicated for my taste. Here is a simpler solution IMHO. I don't see parameter e used anywhere so i removed. Also the use of html form is not needed but I left it as is
Code.gs
function doGet(){
try {
return HtmlService.createHtmlOutputFromFile("HTML_Test");
}
catch(err) {
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": err}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function submitData(data) {
var shid = "your spreadsheet id here";
var ss = SpreadsheetApp.openById(shid);
var sh = ss.getSheetByName("Sheet1");
try {
sh.getRange(sh.getLastRow()+1,1,1,data.length).setValues([data]);
return "success"
}
catch(err) {
sh.getRange(sh.getLastRow()+1,1).setValue(err);
return err;
}
}
HTML_Test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="test">
<p><label>ID</label>
<input type="number" id="ID"/></p>
<p><label>Part Number</label>
<input type="text" id="Part Number"/></p>
<p><label>Description</label>
<input type="text" id="Description"/></p>
<p><label>Item Link</label>
<input type="url" id="Item Link"/></p>
<p><label>Supplier</label>
<input type="text" id="Supplier"/></p>
<p><label>Manufacturer</label>
<input type="text" id="Manufacturer"/></p>
<p><label>Pins</label>
<input type="number" id="Pins"/></p>
<p><label>Size</label>
<input type="text" id="Size"/></p>
<p><label>Order Number</label>
<input type="number" id="Order Number"/></p>
<p><label>Location</label>
<input type="text" id="Location"/></p>
<p><input type="button" value="Submit" onclick="submitForm()"/></p>
</form>
<script>
function submitForm() {
try {
var data = [];
data.push(document.getElementById("ID").value);
data.push(document.getElementById("Part Number").value);
data.push(document.getElementById("Description").value);
data.push(document.getElementById("Item Link").value);
data.push(document.getElementById("Supplier").value);
data.push(document.getElementById("Manufacturer").value);
data.push(document.getElementById("Pins").value);
data.push(document.getElementById("Size").value);
data.push(document.getElementById("Order Number").value);
data.push(document.getElementById("Location").value);
google.script.run.withSuccessHandler(success).submitData(data);
}
catch(err) {
alert(err);
}
}
function success(msg) {
alert(msg);
}
</script>
</body>
</html>

Issue Inserting MySQL Record With Node.js and Handlebars

I am having an issue when trying to submit a form with user information that inserts into a table. I have a userForm that allows user data to be entered with the following:
<form id="userForm">
<fieldset>
<legend>Add User</legend>
<p>First Name: <input id="fname" type="text" name="fname"/></p>
<p>Last Name: <input id="lname" type="text" name="lname"/></p>
<p>Email: <input id="email" type="text" name="email"/></p>
<p>Password: <input id="password" type="text" name="password"/></p>
</fieldset>
<input id="addUser" type="submit" name="add" value="Add User" onclick="addRow()" />
</form>
<script src="script.js"></script>
This then launches the following code in my script.js code:
function addRow(){
var form = document.getElementById("userForm");
var req = new XMLHttpRequest();
// Add the form data to the ajax request
var queryString = "";
var fname = form.fname.value;
var lname = form.lname.value;
var email = form.email.value;
var password = form.password.value;
queryString += "fname=" + fname + "&";
queryString += "lname=" + lname + "&";
queryString += "email=" + email + "&";
queryString += "password=" + password;
req.open('GET', '/insert-user?' + queryString, true);
req.send();
console.log(req.status);
Which executes the server side code:
app.get('/add-user', function(req,res){
var context = {};
res.render('addUser', context);
});
app.get('/insert-user',function(req,res,next){
var context = {};
pool.query("INSERT INTO user (`fname`, `lname`, `email`, `password`) VALUES (?,?,?,?)",
[req.query.fname, req.query.lname, req.query.email, req.query.password],
function(err, result){
if(err){
next(err);
return;
}
context.results = "Inserted id " + result.insertId;
res.render('exerciseTable',context);
});
});
The record is not being inserted into the table. When I console.log(req.status) I see 0 in the console. The add-user page is the form that the user fills out and then the insert-user code is called but it does not seem to be working. In fact, the URL does not change from http://18.219.103.143:3000/add-user to http://18.219.103.143:3000/insert-user? when I submit. It just stays static. It seems like my app.get('/insert-user'... code isn't even being called. Does anyone know what I am missing?
I am getting this error in the console:
Try to put
<form id="userForm" onsubmit="return false;">
Otherwise the default action on your form will be called. As your button is a submit button and that your default action is not set so it defaults to the same page and returning nothing or true will reload your page.

Validation from submitting in Apps Script

Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,
In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.