跳到主要内容

为草稿上传附件

附件需要绑定到已存在的草稿。先创建草稿,再为每个附件创建独立上传会话并上传文件流。

调用顺序​

  1. 创建草稿,取得 message.id。
  2. 调用创建附件上传会话。
  3. 使用响应中的上传地址或会话标识调用上传文件流。
  4. 完成所有附件后发送草稿,或保留在草稿箱中供人工确认。

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()

上传前校验文件大小、扩展名和内容类型。不要把上传地址写入日志,它可能包含短期有效的会话信息。

参考:原始示例。