Скачать вложения из почты с помощью microsoft graph rest api

Я успешно получаю список писем в папке "Входящие" с помощью Microsoft Graph Graph Rest Api, но мне трудно разобраться с документацией о том, как загрузить вложения из почты.

Например: ответ на этот вопрос stackru говорит о том, чего я намерен достичь, но я не понимаю, что такое message_id в упомянутой конечной точке:https://outlook.office.com/api/v2.0/me/messages/{message_id}/attachments

ОБНОВИТЬ

я смог получить подробную информацию о вложении, используя следующую конечную точку: https://graph.microsoft.com/v1.0/me/messages/%7Bid%7D/attachments и получил следующий ответ.

У меня сложилось впечатление, что ответ, вероятно, будет содержать ссылку для загрузки вложения, однако ответ содержит ключ с именем contentBytes, который, как мне кажется, является зашифрованным содержимым файла.

3 ответа

У меня такая же проблема. Это функция, которую я использовал для ее решения. Обратите внимание, что 'contentBytes' уже закодированы в base64, поэтому вам нужно декодировать их для записи. Вы делаете это с помощью base64.b64decode. Если вы этого не сделаете, ваши файлы будут сохранены, но их будет невозможно прочитать.

      def save_attachments(self, message_id):
        """ Saves the email attachments obtained from MS Graph REST API.       
        """
        # Set the API endpoint. This will give all the attachments for a given email (message_id provided)
        url = f"https://graph.microsoft.com/v1.0/me/messages/{message_id}/attachments"
        
        # using the MS Graph client to make the call as this is a 'delegated' email authorization
        # this will create a flow with a URL and a code for the owner of the email account
        # to authorize its use. You can use requests instead if you have the access in AAD. (Application scenario)
        response = self.user_client.get(url)

        # gets the 'value' part of the json response, which contains all the attachment details
        attachments = response.json()['value']
        
        counter = 0
        # Save the attachment content to a file
        for attachment in attachments:
            counter+=1
            file_name = attachment["name"]        
            content_bytes = attachment["contentBytes"]

            full_file_name = os.path.join(file_path, file_name)
            with open(full_file_name, "wb") as f:
                # converts text to base64 encoded bytes
                # remember to add the import from base64 import b64decode
                decoded_content = b64decode(content_bytes)
                f.write(decoded_content)
            print(f"{counter}. {file_name}.")

За attachment ресурс типа файла contentBytes возврат имущества

base64-закодированное содержимое файла

пример

В следующем примере Node.js показано, как получить свойства вложения вместе с содержимым вложения (существует зависимость от request библиотека):

const attachment = await getAttachment(
    userId,
    mesasageId,
    attachmentId,
    accessToken
);
const fileContent = new Buffer(attachment.contentBytes, 'base64');
//...

где

const requestAsync = options => {
  return new Promise((resolve, reject) => {
    request(options, (error, res, body) => {
      if (!error && res.statusCode == 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
};

const getAttachment = (userId, messageId, attachmentId, accessToken) => {
  return requestAsync({
    url: `https://graph.microsoft.com/v1.0/users/${userId}/messages/${messageId}/attachments/${attachmentId}`,
    method: "GET",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      Accept: "application/json;odata.metadata=none"
    }
  }).then(data => {
    return JSON.parse(data);
  });
};

Обновить

В следующем примере показано, как загрузить вложение в виде файла в браузере.

try {
  const attachment = await getAttachment(
    userId,
    mesasageId,
    attachmentId,
    accessToken
  );

  download("data:application/pdf;base64," +  attachment.contentBytes, "Sample.pdf","application/pdf");
} catch (ex) {
  console.log(ex);
}

где

async function getAttachment(userId, messageId, attachmentId, accessToken){
    const res = await fetch(
      `https://graph.microsoft.com/v1.0/users/${userId}/messages/${messageId}/attachments/${attachmentId}`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${accessToken}`,
          Accept: "application/json;odata.metadata=none"
        }
      }
    );
    return res.json();
 }

Зависимость: download.js библиотека

Я не знаю, поможет ли это, но вам просто нужно добавить / $ value в конце вашего запроса:

https://graph.microsoft.com/v1.0/me/messages/{message_id}/attachments/{attachment_id}/$value

Другие вопросы по тегам