简体   繁体   中英

Google Apps Script - send pdf in email

I have a script that sends an email. I would like to set it up so that the email is sent with a pdf attachment that is in my google drive. The name of the file is pdfholder.pdf

Here is the code that is currently working (without attachment), and sending emails

MailApp.sendEmail(userEmail, subject, message);

Here is the code that is not working (with the attachment), and not sending emails

var file = DocsList.getFileById('pdfholder');
MailApp.sendEmail(userEmail, subject, message, {attachments:file});

Any ideas on how to get this working? I am new to google apps scripting so simple/thorough explanations would be much appreciated. Thanks!

The argument needed for the optional argument attachment is an array (as clearly shown in the documentation ). This is to allow for easy handling of multiple attached files. In you case it will be an array of one single element : [file] so your final code would (indeed) be

MailApp.sendEmail(userEmail, subject, message, {attachments:[file]});

The official doc has an example exactly for this purpose too:

// Send an email with two attachments: a file from Google Drive (as a PDF) and an HTML file.
 var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
 var blob = Utilities.newBlob('Insert any HTML content here', 'text/html', 'my_document.html');
 MailApp.sendEmail('mike@example.com', 'Attachment example', 'Two files are attached.', {
     name: 'Automatic Emailer Script',
     attachments: [file.getAs(MimeType.PDF), blob]
 });

See: https://developers.google.com/apps-script/reference/mail/mail-app

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