简体   繁体   中英

Name email attachment in Google Apps Script

I have the following GAS 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM