Does the documentation mean what it says? The 3.1 library reference says quopri.encodestring takes a string, but feeding it a string results in an error.

quopri.encodestring(s[, quotetabs])
Like encode(), except that it accepts a source string and returns the corresponding encoded string.

However, feeding this a str results in an error

import quopri

enctext = quopri.encodestring('hello')
print(enctext)

results in

TypeError: argument 1 must be bytes or buffer, not str.

??

The source string has to be a string of bytes, just like you would get from a binary read of a file.
So try:

import quopri

enctext = quopri.encodestring(b'hello')
print(enctext)
print(type(enctext))

Here is a mildly better example:

# using Python module quopri for MIME strings used in emails
# Python 3.1

import quopri

mystring = '\u00bfC\u00f3mo es usted?'
bytestring = mystring.encode("utf8")

# the MIME string you send
enctext = quopri.encodestring(bytestring)
print(enctext)
print(type(enctext))

# the MIME string you receive
dectext = quopri.decodestring(enctext)
print(dectext)
print(type(dectext))

# convert to printable regular string
print(dectext.decode("utf8"))

"""my result -->
b'=C2=BFC=C3=B3mo es usted?'
<class 'bytes'>
b'\xc2\xbfC\xc3\xb3mo es usted?'
<class 'bytes'>
¿Cómo es usted?
"""

Just imagine that the escaped bytes could be from an image source.

If you send unicode strings out, please notice that:

# a string with \u unicode characters
mystring = '\u00bfC\u00f3mo es usted?'
# or ...
mystring = "¿Cómo es usted?"
bytestring = mystring.encode("utf8")

This gives the same bytestring that can be used with quopri.encodestring(bytestring) in the code I mentioned. Bytestrings (bytearrays) are probably the reason why the unicode() function has been dropped from Python3.

# -*- coding: iso-8859-15 -*-

from email.mime.text import MIMEText
import quopri

mystring = "¿Cómo es usted?"
bytestring = mystring.encode("utf8")
enctext = quopri.encodestring(bytestring)

msg = MIMEText(enctext)

Fails with

Traceback (most recent call last):
File "test.py", line 10, in <module>
msg = MIMEText(enctext)
File "C:\Program Files\python31\lib\email\mime\text.py", line 30, in __init__
self.set_payload(_text, _charset)
File "C:\Program Files\python31\lib\email\message.py", line 234, in set_payloa
d
self.set_charset(charset)
File "C:\Program Files\python31\lib\email\message.py", line 269, in set_charse
t
cte(self)
File "C:\Program Files\python31\lib\email\encoders.py", line 60, in encode_7or
8bit
orig.encode('ascii')
AttributeError: 'bytes' object has no attribute 'encode'

Same fate without the quopri line

This article has been dead for over six months. Start a new discussion instead.