调用“创建草稿”接口,从返回结果中获取到id,也就是草稿id,再调用“发送草稿箱中的邮件”接口,发出邮件。
相关接口
基本流程
Python示例代码
重要
风险提示:下述代码在Python 3.11.9进行的测试,用于生产环境之前请务必先做好测试。
# -*- coding: utf-8 -*-
import email
import requests
# 导入获取访问令牌的函数,路径根据实际情况进行修改,或直接给access_token赋值用于测试
from api_demo.get_access_token import access_token
def 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"]
}
}
# 调用函数创建邮件草稿并获取草稿ID
email_id = create_draft(email_account, v_payload)
print(f'id: {email_id}')
# 发送草稿
send_drafts(email_account, email_id)
print('发送完成')
运行结果
文档内容是否对您有帮助?