为草稿上传附件
附件需要绑定到已存在的草稿。先创建草稿,再为每个附件创建独立上传会话并上传文件流。
调用顺序
Python 示例
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()
上传前校验文件大小、扩展名和内容类型。不要把上传地址写入日志,它可能包含短期有效的会话信息。
参考:原始示例。