API开放平台场景示例:创建草稿并发送邮件
时间:2025-05-02 11:43:25 作者:喜米网络 来源:阿里云调用“创建草稿”接口,从返回结果中获取到id,也就是草稿id,再调用“发送草稿箱中的邮件”接口,发出邮件。
说明
批量或系统类邮件建议走邮件推送产品(什么是邮件推送)的SMTP或API发信方式。
企业邮箱API接口发信仅适合特殊场景使用,需要多个接口联动。
相关接口
基本流程

Python示例代码
重要
风险提示:下述代码在Python 3.11.9进行的测试,用于生产环境之前请务必先做好测试。
# -*- coding: utf-8 -*-import emailimport requests# 导入获取访问令牌的函数,路径根据实际情况进行修改,或直接给access_token赋值用于测试from api_demo.get_access_token import access_tokendef create_draft(email_account, payload): """
接口名称:创建草稿
文档:https://mailhelp.aliyun.com/openapi/index.html#/operations/alimailpb_alimail_mailagent_open_MailService_CreateMessage
参数:
email (str): 用户邮箱地址
payload (dict): 邮件内容的JSON格式数据
返回:
str: 创建的邮件草稿的ID
"""
# 构造请求URL
url = f"https://alimail-cn.aliyuncs.com/v2/users/{email_account}/messages"
# 构造请求头,包括内容类型和授权令牌
headers = {'Content-Type': 'application/json', 'Authorization': 'bearer ' + access_token} # 发送POST请求,创建邮件草稿
response = requests.request("POST", url, json=payload, headers=headers) # 打印请求和响应的详细信息
print('##########################################################################') print('请求参数:', payload) print('返回参数:', response.status_code, response.text) print('##########################################################################') # 返回邮件草稿的ID
return response.json()["message"]["id"]def send_drafts(email_account, v_id): """
发送草稿箱中的邮件
文档:https://mailhelp.aliyun.com/openapi/index.html#/operations/alimailpb_alimail_mailagent_open_MailService_SendMessage
"""
url = f"https://alimail-cn.aliyuncs.com/v2/users/{email_account}/messages/{v_id}/send"
payload = {"saveToSentItems": True}
headers = {'Content-Type': 'application/json', 'Authorization': 'bearer ' + access_token}
response = requests.request("POST", url, json=payload, headers=headers) print('##########################################################################') print('请求参数:', payload) print('返回参数:', response.status_code, response.text) print('##########################################################################')# 定义邮箱地址和邮件内容的JSON格式数据email_account = "test@example.com"v_payload = { "message": { "internetMessageId": email.utils.make_msgid(), "subject": "主题", "summary": "摘要", "priority": "PRY_NORMAL", "isReadReceiptRequested": True, "from": { "email": "test@example.com", "name": "test"
}, "toRecipients": [
{ "email": "test@example.com", "name": "to"
}
], "ccRecipients": [
{ "email": "test@example.com", "name": "cc"
}
], "bccRecipients": [
{ "email": "test@example.com", "name": "bcc"
}
], "replyTo": [
{ "email": "test@example.com", "name": "replyTo"
}
], "body": { "bodyText": "bodyText", "bodyHtml": "<h1>bodyHtml</h1>"
}, "internetMessageHeaders": { "property1": "string", "property2": "string"
}, "tags": ["string"]
}
}# 调用函数创建邮件草稿并获取草稿IDemail_id = create_draft(email_account, v_payload)print(f'id: {email_id}')# 发送草稿send_drafts(email_account, email_id)print('发送完成')运行结果


上一篇:快速入门
