API Open Platform code example: Get an access credential

更新时间:
复制 MD 格式

A mailbox administrator obtains an Application ID and Secret from the API Open Platform in the mailbox admin console. The administrator adds an application, checks the required permissions, and saves the configuration.

Related API

Get an access credential

Basic flow

image

Python code example

Note
  • If you do not want to fetch the key value from an environment variable, pass it directly as a string. For example:

client_id ='xxxxxx'

client_secret ='xxxxxx'

Important

Important: This code was tested on Python 3.11.9. Test it thoroughly before you use it in a production environment.

# -*- coding: utf-8 -*-
import os
import requests
from datetime import datetime, timedelta


def get_access_token():
    """
    Get an access credential.

    This function gets an access credential (access_token) by sending a request
    to the Alibaba Mail OAuth 2.0 API. It uses a client ID and client secret
    from environment variables for authentication.
    """
    # Print the API name and document link.
    print('API name:', 'Get an access credential, Document: https://mailhelp.aliyun.com/openapi/index.html#/markdown/authorization.md')
    # Define the API URL.
    interface_url = "https://alimail-cn.aliyuncs.com/oauth2/v2.0/token"
    # Set the request header to specify the content type.
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}

    # Get the client ID and secret from environment variables.
    client_id = os.getenv('ALIMAIL_CLIENT_ID')  # Get the ALIMAIL_CLIENT_ID environment variable, which must be set in advance.
    client_secret = os.getenv('ALIMAIL_CLIENT_SECRET')  # Get the ALIMAIL_CLIENT_SECRET environment variable, which must be set in advance.

    # Check if the client ID and secret are set.
    if not client_id or not client_secret:
        raise ValueError("Environment variables ALIMAIL_CLIENT_ID and ALIMAIL_CLIENT_SECRET must be set!")

    # Prepare the request data.
    data = {
        "grant_type": "client_credentials",
        "client_id": client_id,
        "client_secret": client_secret
    }
    try:
        # Send a POST request.
        response = requests.post(interface_url, headers=headers, data=data)
        # Print the parameters returned by the API.
        print(f'Parameters returned by the API: {response.json()}')

        # Parse the response into a dictionary.
        response_json = response.json()
        # Fetch the token type and expiration time.
        token_type = response_json["token_type"]
        expires_in = response_json["expires_in"]
        # Print the token type.
        print(f'token_type: {token_type}')
        # Calculate the expiration time.
        current_time = datetime.now()
        expiration_time = current_time + timedelta(seconds=expires_in)
        # Print the expiration time.
        print(f"expires_in: {round(expires_in / 3600)} hours,end_time:", expiration_time.strftime("%Y-%m-%d %H:%M:%S"))

        # Return the access credential.
        return response_json["access_token"]
    except requests.RequestException as e:
        # Handle request failure exceptions.
        print(f"Request failed: {e}")
    except (KeyError, ValueError) as e:
        # Handle response parsing exceptions.
        print(f"Failed to parse the response: {e}")


# Call the function to get the access credential and print it.
access_token = get_access_token()
print(f'access_token: {access_token}')

Execution result

image