(root)/
Python-3.12.0/
Lib/
email/
encoders.py
       1  # Copyright (C) 2001-2006 Python Software Foundation
       2  # Author: Barry Warsaw
       3  # Contact: email-sig@python.org
       4  
       5  """Encodings and related functions."""
       6  
       7  __all__ = [
       8      'encode_7or8bit',
       9      'encode_base64',
      10      'encode_noop',
      11      'encode_quopri',
      12      ]
      13  
      14  
      15  from base64 import encodebytes as _bencode
      16  from quopri import encodestring as _encodestring
      17  
      18  
      19  def _qencode(s):
      20      enc = _encodestring(s, quotetabs=True)
      21      # Must encode spaces, which quopri.encodestring() doesn't do
      22      return enc.replace(b' ', b'=20')
      23  
      24  
      25  def encode_base64(msg):
      26      """Encode the message's payload in Base64.
      27  
      28      Also, add an appropriate Content-Transfer-Encoding header.
      29      """
      30      orig = msg.get_payload(decode=True)
      31      encdata = str(_bencode(orig), 'ascii')
      32      msg.set_payload(encdata)
      33      msg['Content-Transfer-Encoding'] = 'base64'
      34  
      35  
      36  def encode_quopri(msg):
      37      """Encode the message's payload in quoted-printable.
      38  
      39      Also, add an appropriate Content-Transfer-Encoding header.
      40      """
      41      orig = msg.get_payload(decode=True)
      42      encdata = _qencode(orig)
      43      msg.set_payload(encdata)
      44      msg['Content-Transfer-Encoding'] = 'quoted-printable'
      45  
      46  
      47  def encode_7or8bit(msg):
      48      """Set the Content-Transfer-Encoding header to 7bit or 8bit."""
      49      orig = msg.get_payload(decode=True)
      50      if orig is None:
      51          # There's no payload.  For backwards compatibility we use 7bit
      52          msg['Content-Transfer-Encoding'] = '7bit'
      53          return
      54      # We play a trick to make this go fast.  If decoding from ASCII succeeds,
      55      # we know the data must be 7bit, otherwise treat it as 8bit.
      56      try:
      57          orig.decode('ascii')
      58      except UnicodeError:
      59          msg['Content-Transfer-Encoding'] = '8bit'
      60      else:
      61          msg['Content-Transfer-Encoding'] = '7bit'
      62  
      63  
      64  def encode_noop(msg):
      65      """Do nothing."""