Tutorials>Learn how to download message attachments from message store - PHP

A tutorial to teach you how to download message attachments from user's message store. Click the "Start" button below to start the tutorial.

Start Tutorial

Clone and Setup the project

Clone the project from GitHub and install RingCentral PHP SDK and dependencies.

Create a RingCentral app

If you don't know how to create a RingCentral app. Click https://developer.ringcentral.com/library/getting-started.html for instructions.

Set Environment Variables

Copy the Client id and Client secret and add them to the environment/.env-sandbox file.

RC_CLIENT_ID=
RC_CLIENT_SECRET=

Add the account login credentials to the environment/.env-sandbox file.

RC_USERNAME=
RC_PASSWORD=
RC_EXTENSION=

If you want to specify variables for your production environment, repeat this step for the environment/.env-production file.

Login using RingCentral PHP SDK

Using a RingCentral SDK is the most convenient way to authenticate and access RingCentral platform services.

After login successfully, we call the function read_message_store_message_content() to read and download the content.

Read the user's message store

We call the "message-store" endpoint and specify the time period using the dateFrom and dateTo query parameters.

You can change the dateFrom and dateTo values, or specify other query parameters such as messageType, direction etc. if you want.

Get ready to parse the response

We parse the JSON response and get the amount of items from the records array.

We also create a "content" folder to store message attachments.

To get ready for downloading a big amount of attachments, we need to limit API calls to meet the "Usage Plan Group" requirement to avoid exceeding API rate limit. For this API endpoint, it is 40 API calls per minute. For that purpose, we use the $timePerApiCall variable to cause a delay between API calls.

Detect the message type

Each record may contain several attachments. We iterate through the attachments array, detect the message type to create a file name and file name extension accordingly.

We implement the getFileExtensionFromMimeType() function to specify the filename extension based on the attachment contentType.

Download and save the message attachment

We download the attachment by calling the $platform->get() function to get the content from the $attachment->uri.

Finally, we save the data to a file under the content folder.

Cause delay and read the next attachment

We calculate the $consumed time it took to read and save an attachment, and cause a delay if the $consumed time is less than the $timePerApiCall. Otherwise, we move on to download the next attachment.