Omid
Omid

Reputation: 177

Name email attachment in Google Apps Script

I have the following G.A.S script to email a google sheet as a pdf attachment.

  var spreadsheet = SpreadsheetApp.getActive();
  var subject = spreadsheet.getRange("U1:U1").getValues();
  var emailTo = spreadsheet.getRange("V1:V1").getValues();
  var message = spreadsheet.getRange("W1:W1").getValues();
  var pdf = DriveApp.getFileById(spreadsheet.getId()).getAs('application/pdf').getBytes();
  var attach = {fileName:subject,content:pdf, mimeType:'application/pdf'};
  MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});

The above code works well except that the file attached to the email message has a bizarre name like "[Ljava.lang.Object_@4e63998c" with no ".pdf" extension! I am looking for a way to set a name for the pdf file before being attached to the email. The file name should equal the "subject" variable.

Thanks in advance. Omid

Upvotes: 3

Views: 2245

Answers (2)

0xh8h
0xh8h

Reputation: 3509

I'm a bit late, but another way to solve this problem might be:

var spreadsheet = SpreadsheetApp.getActive();
var subject = spreadsheet.getRange("U1:U1").getValues();
var emailTo = spreadsheet.getRange("V1:V1").getValues();
var message = spreadsheet.getRange("W1:W1").getValues();

var pdf = DriveApp.getFileById(spreadsheet.getId())
                  .getAs('application/pdf')
                  .getBlob()
                  .setName(subject);

MailApp.sendEmail(emailTo, subject, message, {attachments:[pdf]});

The Blob class has a setName method https://developers.google.com/apps-script/reference/base/blob#setName(String), that can be chained into a Blob object (which is the result of getBlob())

After that you just need to add the Blob object inside attachments array of function MailApp.sendEmail

Upvotes: 0

Tanaike
Tanaike

Reputation: 201503

Values retrieved by getValues() is 2 dimensional array. I think that the filename becomes such string because the array is used as the filename. Please retrieve the element from the array and try again. So could you please modify as follows?

From :

var attach = {fileName:subject,content:pdf, mimeType:'application/pdf'};

To :

var attach = {fileName:subject[0][0],content:pdf, mimeType:'application/pdf'};

You can also use the following modification. In this case, getValue() can retrieve the value as a string from the cell "U1".

From :

var subject = spreadsheet.getRange("U1:U1").getValues();

To :

var subject = spreadsheet.getRange("U1:U1").getValue();

Reference :

If this was not what you want, please tell me. I would like to think of other solutions.

Upvotes: 1

Related Questions