python-3.x 如何使用xml在SOAP请求中添加附件?

k7fdbhmy  于 2023-04-13  发布在  Python
关注(0)|答案(1)|浏览(167)
strXml ="""<?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>hello</IsBodyHtml>
          <Server></Server>
          <Debug>string</Debug>
          <GUID>{12344-3434-34334-3434343-65656565h5h}</GUID>
          <Attachments></Attachments>
          <RelayCount>0</RelayCount>
        </SMTPEmail>
      </soap12:Body>
    </soap12:Envelope>"""

response = requests.post(url,data=strXml, headers=header)
print(response.content)

我可以让它工作来发送消息,但我不知道如何插入我的文件路径(例如:'C:\Users\name\Downloads\test1.xlsx')在Attachments标签中,以将其附加到电子邮件中。

qq24tv8q

qq24tv8q1#

原来我需要像这样把我的文件转换成hexbinary:

import binascii

def fileAttachmentHex(filepath):

    file = open(filepath,'rb').read()
    file_encode = binascii.hexlify(file)
    return file_encode.decode('utf-8')

然后将十六进制代码的输出插入附件标记中,文件名如下所示:

<Attachments>test1.xlsx:GSDBSG0033043H3G0000000000000</Attachments>

相关问题