473,797 Members | 3,199 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems with email.Generator .Generator

Hi All,

The following piece of code is giving me issues:

from email.Charset import Charset,QP
from email.MIMEText import MIMEText
charset = Charset('utf-8')
charset.body_en coding = QP
msg = MIMEText(
u'Some text with chars that need encoding: \xa3',
'plain',
)
msg.set_charset (charset)
print msg.as_string()

Under Python 2.4.2, this produces the following output, as I'd expect:

MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="utf-8"

Some text with chars that need encoding: =A3

However, under Python 2.4.3, I now get:

Traceback (most recent call last):
File "test_encoding. py", line 14, in ?
msg.as_string()
File "c:\python24\li b\email\Message .py", line 129,
in
as_string
g.flatten(self, unixfrom=unixfr om)
File "c:\python24\li b\email\Generat or.py", line 82,
in flatten
self._write(msg )
File "c:\python24\li b\email\Generat or.py", line 113,
in _write
self._dispatch( msg)
File "c:\python24\li b\email\Generat or.py", line 139,
in
_dispatch
meth(msg)
File "c:\python24\li b\email\Generat or.py", line 182,
in
_handle_text
self._fp.write( payload)
UnicodeEncodeEr ror: 'ascii' codec can't encode
character
u'\xa3' in position 41:
ordinal not in range(128)

This seems to be as a result of this change:

http://svn.python.org/view/python/br...37910&r2=42272

....which is referred to as part of a fix for this bug:

http://sourceforge.net/tracker/?func...70&atid=105470

Now, is this change to Generator.py in error or am I doing something wrong?

If the latter, how can I change my code such that it works as I'd expect?

cheers,

Chris

--
Simplistix - Content Management, Zope & Python Consulting
- http://www.simplistix.co.uk
Sep 11 '06 #1
20 2923
Chris Withers ha scritto:
Hi All,

The following piece of code is giving me issues:

from email.Charset import Charset,QP
from email.MIMEText import MIMEText
charset = Charset('utf-8')
charset.body_en coding = QP
msg = MIMEText(
u'Some text with chars that need encoding: \xa3',
'plain',
)
msg.set_charset (charset)
print msg.as_string()

Under Python 2.4.2, this produces the following output, as I'd expect:
[...]
However, under Python 2.4.3, I now get:
Try with:

msg = MIMEText(
u'Some text with chars that need encoding: \xa3',
_charset='utf-8',
)
and you will obtain the error:
Traceback (most recent call last):
File "<pyshell#4 >", line 3, in -toplevel-
_charset='utf-8',
File "C:\Python2.4\l ib\email\MIMETe xt.py", line 28, in __init__
self.set_payloa d(_text, _charset)
File "C:\Python2.4\l ib\email\Messag e.py", line 218, in set_payload
self.set_charse t(charset)
File "C:\Python2.4\l ib\email\Messag e.py", line 260, in set_charset
self._payload = charset.body_en code(self._payl oad)
File "C:\Python2.4\l ib\email\Charse t.py", line 366, in body_encode
return email.base64MIM E.body_encode(s )
File "C:\Python2.4\l ib\email\base64 MIME.py", line 136, in encode
enc = b2a_base64(s[i:i + max_unencoded])
UnicodeEncodeEr ror: 'ascii' codec can't encode character u'\xa3' in
position 41: ordinal not in range(128)


Regards Manlio Perillo
Sep 11 '06 #2
Manlio Perillo wrote:
Try with:

msg = MIMEText(
u'Some text with chars that need encoding: \xa3',
_charset='utf-8',
)
and you will obtain the error:

Traceback (most recent call last):
File "<pyshell#4 >", line 3, in -toplevel-
_charset='utf-8',
File "C:\Python2.4\l ib\email\MIMETe xt.py", line 28, in __init__
self.set_payloa d(_text, _charset)
File "C:\Python2.4\l ib\email\Messag e.py", line 218, in set_payload
self.set_charse t(charset)
File "C:\Python2.4\l ib\email\Messag e.py", line 260, in set_charset
self._payload = charset.body_en code(self._payl oad)
File "C:\Python2.4\l ib\email\Charse t.py", line 366, in body_encode
return email.base64MIM E.body_encode(s )
File "C:\Python2.4\l ib\email\base64 MIME.py", line 136, in encode
enc = b2a_base64(s[i:i + max_unencoded])
UnicodeEncodeEr ror: 'ascii' codec can't encode character u'\xa3' in
position 41: ordinal not in range(128)
OK, but I fail to see how replacing one unicode error with another is
any help... :-S

Chris

--
Simplistix - Content Management, Zope & Python Consulting
- http://www.simplistix.co.uk
Sep 11 '06 #3
Chris Withers wrote:
The following piece of code is giving me issues:

from email.Charset import Charset,QP
from email.MIMEText import MIMEText
charset = Charset('utf-8')
charset.body_en coding = QP
msg = MIMEText(
u'Some text with chars that need encoding: \xa3',
'plain',
)
msg.set_charset (charset)
print msg.as_string()

Under Python 2.4.2, this produces the following output, as I'd expect:

MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="utf-8"

Some text with chars that need encoding: =A3

However, under Python 2.4.3, I now get:

Traceback (most recent call last):
File "test_encoding. py", line 14, in ?
msg.as_string()
File "c:\python24\li b\email\Message .py", line 129,
in
as_string
g.flatten(self, unixfrom=unixfr om)
File "c:\python24\li b\email\Generat or.py", line 82,
in flatten
self._write(msg )
File "c:\python24\li b\email\Generat or.py", line 113,
in _write
self._dispatch( msg)
File "c:\python24\li b\email\Generat or.py", line 139,
in
_dispatch
meth(msg)
File "c:\python24\li b\email\Generat or.py", line 182,
in
_handle_text
self._fp.write( payload)
UnicodeEncodeEr ror: 'ascii' codec can't encode
character
u'\xa3' in position 41:
ordinal not in range(128)

This seems to be as a result of this change:

http://svn.python.org/view/python/br...37910&r2=42272
>
...which is referred to as part of a fix for this bug:

http://sourceforge.net/tracker/?func...70&atid=105470
>
Now, is this change to Generator.py in error or am I doing something
wrong?
I'm not familiar enough with the email package to answer that.
If the latter, how can I change my code such that it works as I'd expect?
email.Generator and email.Message use cStringIO.Strin gIO internally, which
can't cope with unicode. A quick fix might be to monkey-patch:

from StringIO import StringIO
from email import Generator, Message
Generator.Strin gIO = Message.StringI O = StringIO
# your code here

Peter
Sep 11 '06 #4
Peter Otten wrote:
http://sourceforge.net/tracker/?func...70&atid=105470
>Now, is this change to Generator.py in error or am I doing something
wrong?

I'm not familiar enough with the email package to answer that.
I'm hoping someone around here is ;-)
>If the latter, how can I change my code such that it works as I'd expect?

email.Generator and email.Message use cStringIO.Strin gIO internally, which
can't cope with unicode. A quick fix might be to monkey-patch:
I'm not sure that's correct, but I'm happy to stand corrected.

My understanding is that the StringIO's don't mind as long as they type
is consistent - ie: con't mix unicode and encoded strings, 'cos it
forced python's default ascii codec to kick in and spew unicode errors.

Now, I want to know what I'm supposed to do when I have unicode source
and want it to end up as either a text/plain or text/html mime part.

Is there a how-to for this anywhere? The email package's docs are short
on examples involving charsets, unicode and the like :-(

Chris

--
Simplistix - Content Management, Zope & Python Consulting
- http://www.simplistix.co.uk
Sep 11 '06 #5
Chris Withers wrote:
Peter Otten wrote:
>>http://sourceforge.net/tracker/?func...70&atid=105470
>>>Now, is this change to Generator.py in error or am I doing something
wrong?

I'm not familiar enough with the email package to answer that.


I'm hoping someone around here is ;-)

>>>If the latter, how can I change my code such that it works as I'd expect?

email.Generat or and email.Message use cStringIO.Strin gIO internally, which
can't cope with unicode. A quick fix might be to monkey-patch:


I'm not sure that's correct, but I'm happy to stand corrected.

My understanding is that the StringIO's don't mind as long as they type
is consistent - ie: con't mix unicode and encoded strings, 'cos it
forced python's default ascii codec to kick in and spew unicode errors.

Now, I want to know what I'm supposed to do when I have unicode source
and want it to end up as either a text/plain or text/html mime part.

Is there a how-to for this anywhere? The email package's docs are short
on examples involving charsets, unicode and the like :-(
Well, it would seem like the easiest approach is to monkey-patch the use
of cStringIO to StringIO as recommended and see if that fixes your
problem. Wouldn't it?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 11 '06 #6

Chris Withers wrote:
>
Now, I want to know what I'm supposed to do when I have unicode source
and want it to end up as either a text/plain or text/html mime part.

Is there a how-to for this anywhere? The email package's docs are short
on examples involving charsets, unicode and the like :-(
no expert in this, but have you tried the codecs module?

http://docs.python.org/lib/codec-objects.html

( with 'xmlcharrefrepl ace' for the html )?

Gerard

Sep 11 '06 #7
Chris Withers ha scritto:
[...]

OK, but I fail to see how replacing one unicode error with another is
any help... :-S

The problem is simple: email package does not support well Unicode strings.

For now I'm using this:

charset = "utf-8" # the charset to be used for email
class HeadersMixin(ob ject):
"""A custom mixin, for automatic internationaliz ed headers
support.
"""

def __setitem__(sel f, name, val, **_params):
if isinstance(val, str):
try:
# only 7 bit ascii
val.decode("us-ascii")
except UnicodeDecodeEr ror:
raise ValueError("8 bit strings not accepted")

return self.add_header (name, val)
else:
try:
# to avoid unnecessary trash
val = val.encode('us-ascii')
except:
val = Header.Header(v al, charset).encode ()

return self.add_header (name, val)
class MIMEText(Header sMixin, _MIMEText.MIMET ext):
"""A MIME Text message that allows only Unicode strings, or plain
ascii (7 bit) ones.
"""

def __init__(self, _text, _subtype="plain "):
_charset = charset

if isinstance(_tex t, str):
try:
# only 7 bit ascii
_text.decode("u s-ascii")
_charset = "us-ascii"
except UnicodeDecodeEr ror:
raise ValueError("8 bit strings not accepted")
else:
_text = _text.encode(ch arset)

return _MIMEText.MIMET ext.__init__(se lf, _text, _subtype, _charset)
class MIMEMultipart(H eadersMixin, _MIMEMultipart. MIMEMultipart):
def __init__(self):
_MIMEMultipart. MIMEMultipart._ _init__(self)

This only accepts Unicode strings or plain ascii strings.


Regards Manlio Perillo
Sep 11 '06 #8
Steve Holden wrote:
>Is there a how-to for this anywhere? The email package's docs are short
on examples involving charsets, unicode and the like :-(
Well, it would seem like the easiest approach is to monkey-patch the use
of cStringIO to StringIO as recommended and see if that fixes your
problem. Wouldn't it?
No, not really, since at best that's a nasty (and I meant really nasty)
hack. I'm using the email package as part of a library that I'm building
which is to be used with various frameworks. Monkey patching modules is
about as bad as it gets in that situation...

At worst, and most likely based on my past experience of (c)StringIO
being used to accumulate output, it won't make a jot of difference...

Chris

--
Simplistix - Content Management, Zope & Python Consulting
- http://www.simplistix.co.uk
Sep 11 '06 #9
Manlio Perillo wrote:
>
The problem is simple: email package does not support well Unicode strings.
Really? All the character set support seems to indicate a fair bit of
thought went into this aspect, although it does appear that no-one
bothered to document it :-(

Chris

--
Simplistix - Content Management, Zope & Python Consulting
- http://www.simplistix.co.uk
Sep 11 '06 #10

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

Similar topics

1
1714
by: Adrien Di Mascio | last post by:
Hi all, While reading the email module documentation, I found an error in a small example given for the as_string() method of the Message class: Here is the given code : (URL : http://python.org/doc/current/lib/module-email.Message.html) from cStringIO import StringIO from email.Generator import Generator
2
4662
by: Martin Körner | last post by:
Hi NG, I am using email module for creating mails with attachment (and then sending via smtplib). If the name of the attachment file is longer than about 60 characters the filename is wrapped in the Content-Disposition header: Content-Disposition: attachment; filename="This is a sample file with a very long filename
0
2026
by: Richard Taylor | last post by:
User-Agent: OSXnews 2.07 Xref: number1.nntp.dca.giganews.com comp.lang.python:437315 Hi I am trying to use py2app (http://undefined.org/python/) to package a gnome-python application called gramps (http://www.gramps-project.org) for MAC OS X.
17
2501
by: Lloyd Sheen | last post by:
This IDE is driving me nuts. I needed another button so I copied an existing one, changed the Text and the id and position by drag and drop. Well then I run and get the following: Control 'Button19' of type 'Button' must be placed inside a form tag with runat=server Can the IDE not do what it is supposed to do. It seems that it is a fight to make it do anything or did I do something wrong? It would seem silly to have to create a...
2
1436
by: Sunny | last post by:
I am using an asp page to access data stored by Microsoft SQL in a SQL server database. I cannot get all values to return, some display as blanks. I am using IIS v5, Microsoft SQL Server 2000, running on Windows Advanced Server 2000 SP4. Here is my asp code, SQL table create statements, CSV example data and output. As can be seen by the output, the pc_model and manufacturer fields display blank although these fields hold text data in...
1
3185
by: jmalone | last post by:
I have a python script that I need to freeze on AIX 5.1 (customer has AIX and does not want to install Python). The python script is pretty simple (the only things it imports are sys and socket). The README file in the Tools/freeze directory of the Python-2.4.4 distribution says the following (and many other things): Previous versions of Freeze used a pretty simple-minded algorithm to
2
1976
by: RYAN1214 | last post by:
How can I use this random password code, and then insert the password into email which is sent to the user after the registration has been finished? thx <html> <head> <title>Javascript: Password Generator</title> <style type="text/css"> input, select { font-family: Verdana, Arial, sans-serif;
2
1470
by: Torsten Bronger | last post by:
Hallöchen! I thought that with the following code snippet, I could generate a MIME email stub: #!/usr/bin/env python # -*- coding: utf-8 -*- from email.MIMEText import MIMEText from email.Generator import Generator import sys
2
1831
by: | last post by:
Hi everyone The following code: scriptPath = os.path.dirname(__file__) (dirpath, dirnames, filenames) = os.walk(scriptPath) print 'dirpath\n' print dirpath print 'dirnames\n' pprint.pprint(dirnames)
0
9537
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,...
1
10209
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
10023
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...
0
9066
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7560
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
6803
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5459
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
3750
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2934
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.