Attaching Files to a Draft
Attachments must be bound to an existing draft. First create the draft, then create a separate upload session for each attachment and upload the file stream.
Call Sequence
- Create a draft and obtain
message.id. - Call Create Attachment Upload Session.
- Use the upload URL or session identifier in the response to call Upload File Stream.
- Once all attachments are complete, send the draft or keep it in the drafts folder for manual confirmation.
Python Example
from pathlib import Path
import requests
API_BASE = "https://alimail-cn.aliyuncs.com"
def upload_attachment(
access_token: str,
mailbox: str,
draft_id: str,
file_path: Path,
) -> None:
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
session = requests.post(
f"{API_BASE}/v2/users/{mailbox}/messages/{draft_id}/attachments/createUploadSession",
headers=headers,
json={"attachment": {"name": file_path.name, "isInline": False}},
timeout=15,
)
session.raise_for_status()
upload_url = session.json()["uploadUrl"]
with file_path.open("rb") as stream:
uploaded = requests.post(
upload_url,
headers={"Authorization": f"Bearer {access_token}"},
data=stream,
timeout=60,
)
uploaded.raise_for_status()
Before uploading, validate the file size, extension, and content type. Do not log the upload URL, as it may contain session information that is valid for a short period.
Reference: Original Example.