0
votes

I have a PDF and fetch its contents and store it in a Blob. However, I"m not able to attach this blob as an attachment to an email using MailApp.sendEmail() The attachments paramter of options says "files to send in an email. Each item is a JavaScript objects with the following properties: String fileName, String mimeType (optional) and String content."

Although, I can set the mimeType to 'application/pdf', it doesn't work - probably because of the encoding involved. Here is a sample code

     var resp = UrlFetchApp.fetch(link); 
      if (resp.getResponseCode() == 200){
        var blob = Utilities.newBlob(resp.getContent());
        Logger.log(blob.getDataAsString());
        //            var pdf = blob.getAs('application/pdf'); 
        var options = {'attachments' : 
                       {'fileName' : 'test',
                        'mimeType' : 'application/pdf',
                        'content' : blob.getDataAsString() //Doesn't work 
                       }
                      };
        MailApp.sendEmail(TO_EMAIL, 'Subject','', options);
      }
2

2 Answers

1
votes

Although the documentation says the attachment content has to be a String, it accepts a byte array as well. Here is the code that works

      var resp = UrlFetchApp.fetch(link); 
      if (resp.getResponseCode() == 200){
        var blob = Utilities.newBlob(resp.getContent());
        Logger.log(blob.getDataAsString());
        //            var pdf = blob.getAs('application/pdf'); 
        var options = {'attachments' : 
                       {'fileName' : 'test',
                        'mimeType' : 'application/pdf',
                        'content' : blob.getBytes()
                       }
                      };
        MailApp.sendEmail(TO_EMAIL, 'Subject','', options)
      }
1
votes

We need to update those docs... you can actually attach Blobs directly without need for the object with filename, mimetype, etc.

 var resp = UrlFetchApp.fetch("www.google.com"); 
 if (resp.getResponseCode() == 200){

The FetchResponse object (aka the variable we are calling 'resp') has the "getBlob" method on it, which means that you an use it wherever you'd want to use a blob without doing anything special:

   MailApp.sendEmail(TO_EMAIL, 'Subject', '', {attachments: resp});

Alternatively, you can get an explicit Blob from the FetchResponse, which is just a nice wrapper around the data with some extra methods. The only obvious reason to do this would be to change the filename or mime type, although note that UrlFetchApp already sets these to reasonable defaults (so if for example you downloaded a pdf named MyFile.pdf, the name and mime type will already be set for you as 'MyFile.pdf' and 'application/pdf').

   var blob = resp.getBlob();
   blob.setName('test');
   MailApp.sendEmail(TO_EMAIL, 'Subject', '', {attachments: blob});
}