Search code examples
python-3.xmimemultipart

Explicitly specifying the boundary in MIME multipart messages?


I know how to use python3's email.mime.multipart.MIMEMultipart class to create various kinds of multipart email messages.

I have a need to do "email surgery" on certain existing multipart messages by taking the body (which contains the various MIME parts) and to remove and add some new parts without changing the rest of the email's headers. In the headers, there is the following sample header:

Content-Type: multipart/mixed;
        boundary="ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"

... where the ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ boundary is used to separate the existing message parts.

I want to use the email.mime.multipart.MIMEMultipart tools to create a new body with modified parts, and I want to use the same ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ boundary between these parts, so that I don't have to go back and change the Content-Type header that already exists among the message's original headers.

It would be ideal if I could specify the exact text of the boundary that I want to use when creating this multipart body, but in python3, it seems like the email.mime.multipart.MIMEMultipart package always creates its own, randomly generated boundary string.

In python3, is there any way to tell the email.mime.multipart.MIMEMultipart software to use a boundary string that I supply?

If not, I can work around this by taking the newly generated message body, extracting its new boundary string (which I'll call "newboundary", and then replacing it with the original boundary (which I'll call "originalboundary"), as follows:

msgbodytext = msgbodytext.replace(newboundary, originalboundary)

But I prefer not to do this, if possible.

Any ideas about how to tell email.mime.multipart.MIMEMultipart to use a boundary string that I specify? Thank you.


Solution

  • I originally misread the docs, and now that I re-read them, I see that this is trivially easy.

    To set my own boundary to the value of the originalboundary variable, I just have to do this:

    msg = email.mime.multipart.MIMEMultipart(boundary=originalboundary)