473,657 Members | 2,507 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

MIME encoding change in Python 2.4.3 (or 2.4.2? 2.4.1?) - problemand solution

I have an application that processes MIME messages. It reads a message from a file,
looks for a text/html and text/plain parts in it, performs some processing on these
parts, and outputs the new message.

Ever since I recently upgraded my Python to 2.4.3, the output messages started to
come out garbled, as a block of junk characters.

I traced the problem back to a few lines that were removed from the email package:
The new Python no longer encodes the payload when converting the MIME message to a
string.

Since my program must work on several computers, each having a different version of
Python, I had to find a way to make it work correctly no matter if msg.as_string()
encodes the payload or not.

Here is a piece of code that demonstrates how to work around this problem:

............... .... code start ............... .
import email
import email.MIMEText
import email.Charset

def do_some_process ing(s):
"""Return the input text or HTML string after processing it in some way."""
# For the sake of this example, we only do some trivial processing.
return s.replace('foo' ,'bar')

msg = email.message_f rom_string(file ('input_mime_ms g','r').read())
utf8 = email.Charset.C harset('UTF-8')
for part in msg.walk():
if part.is_multipa rt():
continue
if part.get_conten t_type() in ('text/plain','text/html'):
s = part.get_payloa d(None, True) # True means decode the payload, which is normally base64-encoded.
# s is now a sting containing just the text or html of the part, not encoded in any way.

s = do_some_process ing(s)

# Starting with Python 2.4.3 or so, msg.as_string() no longer encodes the payload
# according to the charset, so we have to do it ourselves here.
# The trick is to create a message-part with 'x' as payload and see if it got
# encoded or not.
should_encode = (email.MIMEText .MIMEText('x', 'html', 'UTF-8').get_payload () != 'x')
if should_encode:
s = utf8.body_encod e(s)

part.set_payloa d(s, utf8)
# The next two lines may be necessary if the original input message uses a different encoding
# encoding than the one used in the email package. In that case we have to replace the
# Content-Transfer-Encoding header to indicate the new encoding.
del part['Content-Transfer-Encoding']
part['Content-Transfer-Encoding'] = utf8.get_body_e ncoding()

file('output_mi me_msg','w').wr ite(msg.as_stri ng())
............... .... code end ............... .

Hope this helps someone out there.
(Permission is hereby granted for anybody to use this piece of code for any purpose whatsoever)
Nov 28 '06 #1
0 1397

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2729
by: Alberto | last post by:
I am struggling with the php mail function so to allow a multipart mime settings where both the message and any set of attachments can be allowed. Teorically, I'd know how to do. I build up my headers and pass them as the fourth argument of the function mail(). Practically, what happens is that whenever I try to test my script emailing myself, what appears in the email body are the __cleartext__ headers.
0
2333
by: Klaus Bonadt | last post by:
I would like to parse an email, which I receive from a pop3 account. While the subject and the sender's email address are probably easy to determine, the body seems to be more difficult because of multi-part messages in MIME format. I am interested only in the plain text. Do you know an easy way to retrieve plain text of the body from an email message? Maybe a class, which can be constructed using the whole message string as a parameter...
2
5060
by: velle | last post by:
My headache is growing while playing arround with unicode in Python, please help this novice. I have chosen to divide my problem into a few questions. Python 2.3.4 (#1, Feb 2 2005, 12:11:53) on linux2 1) Does " >>>print 'hello' " simply write to sys.stdout?
0
2155
by: José Joye | last post by:
hello, I have to communicate with a web Service for which I received the WSDL below. When trying to generate the client proxy, it gives me the error (see below). After investigation, I have seen that the error is related to the ouput parameter. To my understanding this could be related to the MIME tag. However, I'm by far not a WSDL expert.
2
5033
by: Der tolle Emil | last post by:
Hi! I wrote a little function to send emails which works quite well. I already managed to send attachments correctly (also more than 1 per email) but I am not able to send a HTML mail containing a text only block for non-HTML clients. I will not post the PHP code as I think it is irrelevant, the error lies within the mail header and/or body, so here is the mail I do want to send: FROM: me <foo@bar.com>
0
2506
by: mubx2000 | last post by:
Hi , I'm looking for code (Symbian C++) that can do the following things: 1-Analyzing the (MIME) types (Content-typemContent-transfere-encoding,Mime Version,Conent Description). 2-Download attached files from the (MMS/Email). 3-Uploading to email or (MMS) . 4-Dealing with Multi-Part Messages. Here Is A Methods That Can HelP In doing Decoding:
6
3442
by: Franz Steinhaeusler | last post by:
Hello NG, a little longer question, I'm working on our project DrPython and try fix bugs in Linux, (on windows, it works very good now with latin-1 encoding). On Windows, it works good now, using setappdefaultencoding and the right encoding for open with styled text control with the right encoding the files. (I see the german Umlauts äöü and the "strong 's'" "ß") The case:
0
1208
by: berb.web | last post by:
list - using python's MIMEMultipart() object I've noticed that it interjects a 'MIME-Version' in the interpart header, like so... <snip> --some_MIME_Boundry Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit
7
2935
by: Ron Garret | last post by:
I'm writing a little HTTP server and need to parse request content that is mime-encoded. All the MIME routines in the Python standard library seem to have been subsumed into the email package, which makes this operation a little awkward. It seems I have to do the following: 1. Extract the content-length header from the HTTP request and use that to read the payload. 2. Stick some artificial-looking headers onto the beginning of this...
0
8425
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8326
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8845
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.