擅长:python、mysql、java
<p>我可以通过在MIMEApplication内容中放入一个虚拟的“marker”,然后在生成MIME消息后替换为实际的二进制文本来解决我的问题:</p>
<pre><code>from email.encoders import encode_noop
from email.generator import BytesGenerator
from email.mime.application import MIMEApplication
import io
# Actual binary "file" I want to encode (in real life, this is a file read from disk)
bytesToEncode = b'Q\x0dQ'
# unique marker that we can find and replace after message generation
binarymarker = b'GuadsfjfDaadtjhqadsfqerasdfiojBDSFGgg'
app = MIMEApplication(binarymarker, _encoder=encode_noop)
b = io.BytesIO()
g = BytesGenerator(b)
g.flatten(app, linesep='\r\n') # linesep for HTTP-compliant header line endings
# replace the marker with the actual binary data, then you have the output you want!
body = b.getvalue().replace(binarymarker, bytesToEncode)
</code></pre>
<p>在此之后,<code>body</code>有了我想要的值,而不会弄乱二进制字节:</p>
^{pr2}$
<p>对于多部分消息,只需首先组装多部分消息,然后在最后执行replace()。在</p>