List Emails and Download Attachments
The download process consists of three layers: emails, attachments, and file streams. Each ID belongs to the context of a specific mailbox and must not be reused across mailboxes.
Call Sequence
- Call List emails in a folder and read the complete results using
nextCursor. - Select the target email ID and call List email attachments.
- For the target attachment, call Create an attachment download session.
- Write the response content to a controlled directory and verify the filename, size, and content type.
Python Example
from pathlib import Path
import requests
API_BASE = "https://alimail-cn.aliyuncs.com"
def download_attachment(
access_token: str,
mailbox: str,
message_id: str,
attachment: dict,
output_dir: Path,
) -> Path:
headers = {"Authorization": f"Bearer {access_token}"}
response = requests.get(
f"{API_BASE}/v2/users/{mailbox}/messages/{message_id}/attachments/{attachment['id']}/$value",
headers=headers,
timeout=60,
)
response.raise_for_status()
safe_name = Path(attachment["name"]).name
target = output_dir / safe_name
target.write_bytes(response.content)
return target
Production tasks should restrict the download directory and total size, reject filenames containing path traversal characters, and avoid logging email bodies or temporary download URLs.
Reference: Original example.