You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Google Apps Script中使用SendGrid添加PDF附件失败求助

Fixing Invalid PDF Attachments from Google Drive in SendGrid via Google Apps Script

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 attachments object is correctly formatted—your existing structure looks good, but confirm the type is indeed application/pdf and 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:43:12