Obtain an Access Token
Before calling any business API, first obtain an access token via the OAuth2 client credentials flow. The token should be cached until it expires; do not request a new one for every request.
Request
POST /oauth2/v2.0/token HTTP/1.1
Host: alimail-cn.aliyuncs.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=<client_id>&client_secret=<client_secret>
Python Example
import os
import time
import requests
TOKEN_URL = "https://alimail-cn.aliyuncs.com/oauth2/v2.0/token"
def get_access_token() -> tuple[str, float]:
response = requests.post(
TOKEN_URL,
data={
"grant_type": "client_credentials",
"client_id": os.environ["ALIMAIL_CLIENT_ID"],
"client_secret": os.environ["ALIMAIL_CLIENT_SECRET"],
},
timeout=10,
)
response.raise_for_status()
payload = response.json()
expires_at = time.time() + int(payload["expires_in"])
return payload["access_token"], expires_at
Usage Recommendations
- Store
client_idandclient_secretin a key management service or runtime secrets. - Reserve a refresh window before
expires_atexpires, for example, obtain a new token 5 minutes in advance. - For multi-instance services, use a shared cache with mutual exclusion for refresh to avoid concurrent requests when the token is about to expire.
- Do not print the full response, as it contains the access token.
References: Sample Code, API Open Platform Overview.