You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XML格式的SOAP请求的Attachments标签中插入文件路径?

给SOAP邮件请求添加附件的方法

要在你的SOAP请求里添加附件,核心是把本地文件转成Base64编码(因为XML无法直接传输二进制数据),然后填充到<Attachments>标签中。具体步骤如下:

1. 读取本地文件并转Base64

先编写代码读取目标文件,将其内容编码为Base64字符串:

import base64

# 定义附件本地路径
attachment_path = r'C:\Users\name\Downloads\test1.xlsx'

# 读取文件并转换为Base64编码字符串
with open(attachment_path, 'rb') as f:
    file_content = base64.b64encode(f.read()).decode('utf-8')
file_name = 'test1.xlsx'  # 设置邮件中显示的附件文件名

2. 修改SOAP XML中的标签

多数SOAP邮件服务要求<Attachments>标签包含子节点来描述附件的文件名和编码内容,修改你的strXml部分:

strXml = f"""<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <SMTPEmail xmlns="http://www.test.com/123">
      <ID></ID>
      <EmailAddress>myname@company.com</EmailAddress>
      <To>myname@company.com</To>
      <CC>myname@company.com</CC>
      <BCC></BCC>
      <Subj>hello</Subj>
      <Text>hello</Text>
      <IsBodyHtml>false</IsBodyHtml>  <!-- 注意:该字段应为布尔值true/false,原代码的"hello"是错误值 -->
      <Server></Server>
      <Debug>string</Debug>
      <GUID>{{12344-3434-34334-3434343-65656565h5h}}</GUID>
      <Attachments>
        <Attachment>  <!-- 单个附件节点,多个附件可重复该节点 -->
          <FileName>{file_name}</FileName>
          <Content>{file_content}</Content>
        </Attachment>
      </Attachments>
      <RelayCount>0</RelayCount>
    </SMTPEmail>
  </soap12:Body>
</soap12:Envelope>"""

3. 发送请求(原有代码保持不变)

import requests

# 假设你已定义好请求的url和header
response = requests.post(url, data=strXml, headers=header)
print(response.content)

注意事项

  • 部分SOAP服务的<Attachments>结构可能存在差异(比如子节点名称不同),如果上述结构不生效,建议查看对应服务的WSDL文档确认附件节点的标准格式。
  • 务必修正<IsBodyHtml>字段的值为合法布尔值,否则可能导致请求失败。

内容的提问来源于stack exchange,提问作者jun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:03:18