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

使用Google Apps Script通过URL更新Google联系人照片的问题

Fixing Google Contacts Photo Update via Google Apps Script

Let's break down why your current code isn't working and fix it step by step:

Key Issues in Your Code

  • Missing Authentication: The Google Contacts API requires OAuth 2.0 authorization, but your UrlFetchApp request isn't including the necessary access token. Apps Script can handle this, but you need to ensure the right scopes are enabled.
  • Missing Required Headers: The Contacts API expects a GData-Version header (usually set to 3.0) to work correctly.
  • Unresolved Placeholders: The URL has {userEmail} and {contactID} which need to be replaced with actual values (you can use default for {userEmail} if targeting the current authenticated user).
  • No Error Handling: You're not capturing or logging errors, which makes it hard to debug failed requests.

Corrected Code

Here's an updated version that addresses all these issues:

function addContactPhoto() {
  // Replace these with your actual values
  const contactId = "YOUR_CONTACT_ID_HERE";
  const imageUrl = "http://www.example.com/joe_bloggs.png";
  
  try {
    // Fetch the image blob
    const imageResponse = UrlFetchApp.fetch(imageUrl);
    const imageBlob = imageResponse.getBlob();
    
    // Configure the request options with auth and required headers
    const options = {
      method: "put",
      contentType: imageBlob.getContentType(), // Use the blob's actual content type instead of hardcoding
      payload: imageBlob.getBytes(), // Send raw bytes instead of the blob object directly
      headers: {
        "GData-Version": "3.0",
        "Authorization": "Bearer " + ScriptApp.getOAuthToken() // Get the active user's OAuth token
      },
      muteHttpExceptions: true // Capture error responses instead of throwing immediately
    };
    
    // Use "default" for the user email to target the current authenticated user
    const apiUrl = `https://www.google.com/m8/feeds/photos/media/default/${contactId}`;
    const response = UrlFetchApp.fetch(apiUrl, options);
    
    // Log response for debugging
    console.log("Response Status Code:", response.getResponseCode());
    console.log("Response Content:", response.getContentText());
    
    if (response.getResponseCode() === 200) {
      console.log("Contact photo updated successfully!");
    } else {
      console.error("Failed to update photo:", response.getContentText());
    }
  } catch (error) {
    console.error("Error during photo update:", error.toString());
  }
}

Additional Setup Steps

  • Enable the Contacts API:
    • Go to your Apps Script project > Resources > Advanced Google Services
    • Toggle People API (or legacy Contacts API) to "On" (note: the Contacts API is deprecated, so using People API is recommended for new projects)
  • Authorize the Script:
    • Run the function once, and you'll be prompted to authorize the script with the necessary permissions (it needs access to your contacts and to fetch external URLs)
  • Find Your Contact ID:
    • To get a contact's ID, use the People API to list contacts, or check the long string at the end of the contact's URL in the Google Contacts web interface

Notes

  • If you're starting a new project, consider using the People API instead of the legacy Contacts API, as it's the current supported API. The method for updating photos uses a different endpoint: https://people.googleapis.com/v1/people/{contactId}:updateContactPhoto.
  • Ensure the image you're using is a valid PNG/JPG, and doesn't exceed Google's size limits (usually around 2MB).

内容的提问来源于stack exchange,提问作者Jonno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:12:38