简体   繁体   中英

Python MIME Base64 Encoding

I need to generate a MIME attachment that contains a Base64 encoded file. However what I need to also allow for is encoding the attachment WITHOUT any new lines. The code I have is as followed:

msg_obj = MIMEMultipart()
msg_atch = MIMEBase(mime_type, mime_subtype)
msg_atch.set_payload(file_data)
Encoders.encode_base64(msg_atch)
msg_obj.attach(msg_atch)

What I have tried to perform to remove the new lines in the attach base64 message was this:

msg_obj = MIMEMultipart()
msg_atch = MIMEBase(mime_type, mime_subtype)
msg_atch.set_payload(file_data)
Encoders.encode_base64(msg_atch)
msg_atch.strip()
msg_obj.attach(msg_atch)

However this failed to change the results of the data. If anyone has any ideas on how to allow for this, it would be great.

I noticed in the penultimate line of your 2nd sample code, you call the msg_atch.strip() function. The problem with this is that there isn't any function strip() of MIMEBase .

What you probably want to do is something along the lines of this:

msg_obj = MIMEMultipart()
msg_atch = MIMEBase(mime_type, mime_subtype)
msg_atch.set_payload(file_data)
Encoders.encode_base64(msg_atch)
msg_atch._payload = msg_atch._payload.replace('\n','')
msg_obj.attach(msg_atch)

The MIMEBase._payload string is the actual (in this case, base64) content used by the attachment.

This code will take the inner content of the MIMEBase attachment and eliminate the extra newlines - including the ones inside to provide nice formatting of base64 text for "human readability" (my question is why they even bother). If you just want to get rid of the newlines at the end, just use msg_atch._payload = msg_atch._payload.rstrip('\\n') .

Keep in mind that the header of the attachment ( Content-Type: application/octet-stream and MIME-Version: 1.0 are parts) require these newlines.

Also, try to remember that you shouldn't normally be editing internal variables in this fashion. However, one of the things I find nice about Python is that there are really no private members of a class, so you can modify whatever you want in a class. We can do whatever we want, especially if it's a special condition.

Happy Coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM