@@ -53,6 +53,8 @@ class Settings:
5353def to_bytes (text , encoding = "utf8" ):
5454 """Converts a text (str, bytes, file-like) to encoded bytes"""
5555 # if the text is not a string or bytes, maybe it is a file
56+ if text is None :
57+ text = b""
5658 if not isinstance (text , (str , bytes )):
5759 text = text .read ()
5860 # if it is a unicode string encode it
@@ -61,17 +63,23 @@ def to_bytes(text, encoding="utf8"):
6163 # if it is not a unicode string
6264 elif isinstance (text , bytes ) and encoding != "utf-8" :
6365 text = text .decode (encoding ).encode ("utf-8" )
66+ elif not isinstance (text , bytes ):
67+ raise RuntimeError (f"{ text } is not not in bytes or string" )
6468 return text
6569
6670
6771def to_unicode (text , encoding = "utf8" ):
6872 """Converts a body (str, bytes, file-like) to unicode"""
6973 # if the text is not a string or bytes, maybe it is a file
70- if not isinstance (text , (str , bytes )):
74+ if text is None :
75+ text = ""
76+ elif not isinstance (text , (str , bytes )):
7177 text = text .read ()
7278 # if it is a bytes string encode it
7379 if isinstance (text , bytes ):
7480 text = text .decode (encoding )
81+ elif not isinstance (text , str ):
82+ text = str (text )
7583 return text
7684
7785
@@ -427,11 +435,11 @@ def encoded_or_raw(text):
427435 text = html = None
428436 elif isinstance (body , (list , tuple )):
429437 text , html = body
430- else :
431- if isinstance (body , bytes ):
432- body = body . decode ()
433- if not isinstance ( body , str ):
434- body = str ( body )
438+ if body is not None :
439+ body = to_unicode (body , "utf8" )
440+ if text is not None :
441+ text = to_unicode ( text , "utf8" )
442+ if text is None and body is not None :
435443 if body .lstrip ().startswith ("<html" ) and body .rstrip ().endswith ("</html>" ):
436444 text = self .settings .server == "gae" and body or None
437445 html = body
@@ -440,21 +448,16 @@ def encoded_or_raw(text):
440448 html = None
441449
442450 if (text is not None or html is not None ) and (not raw ):
443- if text is not None :
444- text = to_bytes (body , encoding )
445- if html is not None :
446- html = to_bytes (html , encoding )
447-
448451 # Construct mime part only if needed
449452 if text is not None and html :
450453 # We have text and html we need multipart/alternative
451454 attachment = MIMEMultipart ("alternative" )
452- attachment .attach (MIMEText (text , _charset = "utf-8" ))
453- attachment .attach (MIMEText (html , "html" , _charset = "utf-8" ))
455+ attachment .attach (MIMEText (text ))
456+ attachment .attach (MIMEText (html , "html" ))
454457 elif text is not None :
455- attachment = MIMEText (text , _charset = "utf-8" )
458+ attachment = MIMEText (text )
456459 elif html :
457- attachment = MIMEText (html , "html" , _charset = "utf-8" )
460+ attachment = MIMEText (html , "html" )
458461
459462 if attachments :
460463 # If there are attachments put text and html into
0 commit comments