javascriptgoogle-apps-scriptweb-applications

Google app script: Send mail, inlineImage from js File


I use google.script.run to use the MailApp API in google app script and I pass a mail object like this :

google.script.run.sendMail(mail);

The mail object is structured like this :

  var mail = {
    to:"",
    cc:"",
    subject:"",
    htmlBody:"",
    inlineImages: inlineImages
  }

inlineImages is a Javascript object that map key string to image data (BlobSource) from google ressources

But then I pass File object in inlineImages I get Failed due to illegal value.

EDIT :

I get the inlineImages like this :

var inlineImages

function createImages(event) {
    var file = event.target.files[0];
    var key = "image"+Object.keys(inlineImages).length;

    inlineImages[key] = file;
}

I also try to get Image object :

function createImages(event) {
    var file = event.target.files[0];
    var key = "image"+Object.keys(inlineImages).length;

    var reader = new FileReader();
    reader.onload = function(e) {
        var img = new Image();
        img.src = e.target.result;

        inlineImages[key] = img;
    }

    reader.readAsDataURL(file);
}

Solution

  • FileObject is an illegal parameter.

    Legal parameters and return values are JavaScript primitives like a

    • Number,
    • Boolean,
    • String, or
    • null, as well as
    • JavaScript objects and arrays that are composed of primitives, objects and arrays.
    • A form element within the page is also legal as a parameter, but it must be the function’s only parameter, and it is not legal as a return value

    All other types, including Date and Function are illegal. The only way you're going to get a file past through the above restrictions from client to server are if you convert the fileObject to one of the above types.

    Here, I'll go with form.

    If you call a server function with a form element as a parameter, the form becomes a single object with field names as keys and field values as values. The values are all converted to strings, except for the contents of file-input fields, which become Blob objects.

    But for other types, JSON.stringify on one side and JSON.parse on the other side would work