在Google Apps Script中使用SendGrid添加PDF附件失败求助
Hey there! I see exactly what's tripping you up here—you're pulling the wrong content from Google Drive with that share link, which is why your PDF won't open. Let's break this down and fix it step by step.
The Root Problem
The URL you're using (https://drive.google.com/file/d/19rzCtnOMWw0ZZM4FViMWVZWkRRnsWx3L/view?usp=sharing) is for viewing the file in a browser, not downloading the raw PDF data. When you fetch this link, UrlFetchApp grabs the HTML of the Drive preview page, not the actual PDF content. That's why the attachment size matches (it's the size of the web page) but it's not a valid PDF file.
Solution 1: Use Google Drive Service (Simpler & More Reliable)
Instead of fetching via URL, use Google Apps Script's built-in Drive Service to get the file directly. This avoids any URL trickery and handles permissions smoothly:
// Replace with your file ID (the string after /d/ in your original URL) const fileId = "19rzCtnOMWw0ZZM4FViMWVZWkRRnsWx3L"; const file = DriveApp.getFileById(fileId); // Get the raw PDF content as bytes, then base64 encode it const attachment = Utilities.base64Encode(file.getBlob().getBytes());
Solution 2: Use the Direct Download URL
If you prefer sticking with UrlFetchApp, you can use Drive's direct download URL instead of the view link. Replace your filePath with this format:https://drive.google.com/uc?id=YOUR_FILE_ID&export=download
Here's the updated code for this approach:
const fileId = "19rzCtnOMWw0ZZM4FViMWVZWkRRnsWx3L"; const filePath = `https://drive.google.com/uc?id=${fileId}&export=download`; const response = UrlFetchApp.fetch(filePath); const attachment = Utilities.base64Encode(response.getContent());
Quick Checks to Ensure Success
- Permissions: Make sure the Google Apps Script project has access to the Drive file. If the file is private, run the script once manually to authorize access (you'll get a prompt to grant permissions).
- SendGrid Payload: Double-check that your
attachmentsobject is correctly formatted—your existing structure looks good, but confirm thetypeis indeedapplication/pdfand the filename ends with.pdf.
Either of these methods should give you the raw PDF data that SendGrid needs to attach a valid, openable file. Give it a shot, and you should be all set!
内容的提问来源于stack exchange,提问作者Brawley Reishman

