Carmad94
Carmad94

Reputation: 79

How to get a Gmail user's profile picture using Google Apps Script?

I want to update a user's email signature in our domain workspace. I want to use the user's profile picture as part of the email signature. However, I am unable to render it in the email signature.

Once I've queried the target user, What I did so far are the following:

  1. Used AdminDirectory.Users.Photos.get(email_address) function to get profile photo properties. Used these properties to create an encoded image URL to display it in the HTML img src attribute. So,<img src="data:${userPhoto.mimeType};base64,${userPhoto.photoData}">. But there was no profile picture displayed.

  2. Used the getThumbnailPhotoUrl() function but it renders a default placeholder image even if there was a profile picture set.

I've also added the scope: 'https://www.googleapis.com/auth/admin.directory.user' for the service credential used to update the target user in the domain.

Are there any other ways how to do it?

Upvotes: 0

Views: 2433

Answers (1)

ziganotschka
ziganotschka

Reputation: 26796

users.photos.get should return you the following response:

{
  "kind": "admin#directory#user#photo",
  "id": "112573616946026931368",
  "etag": "\"-vDsmNkFadksL3sdO9_llNHf95VVWFrsahpYPMFRU6U/X6ZsLw-qrvYjOu4FN-GLlBCL-ts\"",
  "primaryEmail": "EMAIL",
  "mimeType": "image/jpeg",
  "height": 96,
  "width": 96,
  "photoData": "photoDataString"
}

whereby photoData is defined as following:

string (bytes format)

The user photo's upload data in web-safe Base64 format in bytes. This means:

The slash (/) character is replaced with the underscore (_) character. The plus sign (+) character is replaced with the hyphen (-) character. The equals sign (=) character is replaced with the asterisk (*). For padding, the period (.) character is used instead of the RFC-4648 baseURL definition which uses the equals sign (=) for padding. This is done to simplify URL-parsing. Whatever the size of the photo being uploaded, the API downsizes it to 96x96 pixels. A base64-encoded string.

Now, you can retrieve the photo blob to e.g. store it on your Drive as following:

function saveUserPhoto() {
  var data = "photoDataString"
  var bytes = Utilities.base64DecodeWebSafe(data)
  var blob = Utilities.newBlob(bytes, "image/png", "userPhoto");
  DriveApp.createFile(blob);
}

Upvotes: 1

Related Questions