調用“創建草稿”接口,從返回結果中獲取到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://mailbestwisewords.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://mailbestwisewords.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('發送完成')
運行結果
文檔內容是否對您有幫助?