Use internal moodles own core_text to encode mimeheaders.
Fall back to phpmailers inbuilt functions if not
194723
public function encodeHeader($str, $position = 'text') {
        $encoded = core_text::encode_mimeheader($str, $this->CharSet);
        if ($encoded !== false) {
            if ($position === 'phrase') {
                // Escape special symbols in each line in the encoded string, join back together and enclose in quotes.
                $chunks = preg_split("/\\n/", $encoded);
                $chunks = array_map(function($chunk) {
                    return addcslashes($chunk, "\0..\37\177\\\"");
                }, $chunks);
                return '"' . join(parent::getLE(), $chunks) . '"';
            }
            return str_replace("\n", parent::getLE(), $encoded);
        }

        return parent::encodeHeader($str, $position);
    }
744116
def _build_message(self, message):
        """"""
        if not message.recipients():
            return False
        recipients = ','.join(message.to)
        recipients_cc = ','.join(message.cc)
        recipients_bcc = ','.join(message.bcc)

        text_body = message.body
        html_body = None
        if isinstance(message, EmailMultiAlternatives):
            for alt in message.alternatives:
                if alt[1] == "text/html":
                    html_body = alt[0]
                    break

        elif getattr(message, 'content_subtype', None) == 'html':
            # Don't send html content as plain text
            text_body = None
            html_body = message.body

        reply_to = ','.join(message.reply_to)
        custom_headers = {}
        if message.extra_headers and isinstance(message.extra_headers, dict):
            if 'Reply-To' in message.extra_headers:
                reply_to = message.extra_headers.pop('Reply-To')
            if len(message.extra_headers):
                custom_headers = message.extra_headers
        attachments = []
        if message.attachments and isinstance(message.attachments, list):
            if len(message.attachments):
                for item in message.attachments:
                    if isinstance(item, tuple):
                        (f, content, m) = item
                        content = base64.b64encode(content)
                        # b64decode returns bytes on Python 3. PMMail needs a
                        # str (for JSON serialization). Convert on Python 3
                        # only to avoid a useless performance hit on Python 2.
                        if not isinstance(content, str):
                            content = content.decode()
                        attachments.append((f, content, m))
                    else:
                        attachments.append(item)

        postmark_message = PMMail(api_key=self.api_key,
                                  subject=message.subject,
                                  sender=message.from_email,
                                  to=recipients,
                                  cc=recipients_cc,
                                  bcc=recipients_bcc,
                                  text_body=text_body,
                                  html_body=html_body,
                                  reply_to=reply_to,
                                  custom_headers=custom_headers,
                                  attachments=attachments)

        postmark_message.tag = getattr(message, 'tag', None)
        postmark_message.track_opens = getattr(message, 'track_opens', False)

        return postmark_message
397859
def header_encode(header_bytes, charset='iso-8859-1'):
    
    if not header_bytes:
        return ""
    if isinstance(header_bytes, str):
        header_bytes = header_bytes.encode(charset)
    encoded = b64encode(header_bytes).decode("ascii")
    return '=?%s?b?%s?=' % (charset, encoded)
291753
public function preSend()
    {
        try {
            $this->mailHeader = '';
            if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
                throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
            }

            // Set whether the message is multipart/alternative
            if (!empty($this->AltBody)) {
                $this->ContentType = 'multipart/alternative';
            }

            $this->error_count = 0; // reset errors
            $this->setMessageType();
            // Refuse to send an empty message unless we are specifically allowing it
            if (!$this->AllowEmpty and empty($this->Body)) {
                throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
            }

            $this->MIMEHeader = $this->createHeader();
            $this->MIMEBody = $this->createBody();

            // To capture the complete message when using mail(), create
            // an extra header list which createHeader() doesn't fold in
            if ($this->Mailer == 'mail') {
                if (count($this->to) > 0) {
                    $this->mailHeader .= $this->addrAppend('To', $this->to);
                } else {
                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
                }
                $this->mailHeader .= $this->headerLine(
                    'Subject',
                    $this->encodeHeader($this->secureHeader(trim($this->Subject)))
                );
            }

            // Sign with DKIM if enabled
            if (!empty($this->DKIM_domain)
                && !empty($this->DKIM_private)
                && !empty($this->DKIM_selector)
                && !empty($this->DKIM_domain)
                && file_exists($this->DKIM_private)) {
                $header_dkim = $this->DKIM_Add(
                    $this->MIMEHeader . $this->mailHeader,
                    $this->encodeHeader($this->secureHeader($this->Subject)),
                    $this->MIMEBody
                );
                $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
                    str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
            }
            return true;

        } catch (phpmailerException $exc) {
            $this->setError($exc->getMessage());
            if ($this->exceptions) {
                throw $exc;
            }
            return false;
        }
    }
434816
static function sendXmlHttpResponseHeaders($contenttype = "application/json", $charset = 'utf-8')
	{
		if ( is_null($charset) )
			$charset = mb_internal_encoding();
			
		// charset
		header("Content-Type: $contenttype; charset=$charset");
		
		// no cache
		header("Expires: Sat, 1 Jan 2005 00:00:00 GMT");
		header("Last-Modified: ".gmdate( "D, d M Y H:i:s")." GMT");
		header("Cache-Control: no-cache, must-revalidate");
		header("Pragma: no-cache");	
	}
1034563
def charset=(charset)
      content_type = parsed_content_type_header.mime_type
      if false == charset
        set_content_type content_type, nil
      else
        set_content_type content_type, charset || self.class.default_charset
      end
    end
591901
public function createMailboxHeader($name, $addresses = null)
    {
        $header = new Swift_Mime_Headers_MailboxHeader($name, $this->encoder, $this->emailValidator, $this->addressEncoder);
        if (isset($addresses)) {
            $header->setFieldBodyModel($addresses);
        }
        $this->setHeaderCharset($header);

        return $header;
    }
1350972
function buildHeaderValue(structured) {
  var paramsArray = [];

  Object.keys(structured.params || {}).forEach(function (param) {
    // filename might include unicode characters so it is a special case
    if (param === 'filename') {
      (0, _emailjsMimeCodec.continuationEncode)(param, structured.params[param], 50).forEach(function (encodedParam) {
        // continuation encoded strings are always escaped, so no need to use enclosing quotes
        // in fact using quotes might end up with invalid filenames in some clients
        paramsArray.push(encodedParam.key + '=' + encodedParam.value);
      });
    } else {
      paramsArray.push(param + '=' + escapeHeaderArgument(structured.params[param]));
    }
  });

  return structured.value + (paramsArray.length ? '; ' + paramsArray.join('; ') : '');
}
43502
private function buildHeaders(Swift_Mime_Message $message)
    {
        $headers = [];
        $filter  = [
            'Bcc',
            'Cc',
            'Content-Transfer-Encoding',
            'Content-Type',
            'Date',
            'DKIM-Signature',
            'DomainKey-Signature',
            'From',
            'Message-ID',
            'MIME-Version',
            'Received',
            'Reply-To',
            'Return-Path',
            'Sender',
            'Subject',
            'To',
        ];

        /** @var Swift_Mime_Header $header */
        foreach ($message->getHeaders()->getAll() as $header) {
            if (in_array($header->getFieldName(), $filter, true)) {
                continue;
            }

            $headers[trim($header->getFieldName())] = trim($header->getFieldBody());
        }

        return $headers;
    }
561502
def set_mimetext_headers(self, message, subject, from_addr, to_addrs, cc_addrs, priority):
        """"""

        message['Subject'] = subject
        message['From'] = from_addr
        message['To'] = ', '.join(to_addrs)
        if cc_addrs:
            message['Cc'] = ', '.join(cc_addrs)

        if priority and self.priority_header_is_valid(priority):
            priority = PRIORITIES[str(priority)].copy()
            for key in priority:
                message[key] = priority[key]

        return message
724094
public function generateHeaders()
    {
        // Workaround for encoded email addresses.
        // When encoded, email addresses (at least the name param) have more characters
        // By default, line length is set to 76 characters, after what a new line is created with $lineBreak.
        // This operation is done during encoding via iconv (see ezcMailTools::composeEmailAddress()).
        // Problem is that this operation is done a 2nd time in ezcMailPart::generateHeaders().
        // Following code ensures that there is no double $lineBreak introduced
        // by this process because it potentially breaks headers
        $lineBreak = ezcMailTools::lineBreak();
        $headers = str_replace( "$lineBreak$lineBreak", $lineBreak, parent::generateHeaders() );
        return $headers;
    }
1348038
def canonicalize(message):
    

    if message.is_multipart() \
            or message.get('Content-Transfer-Encoding') != 'binary':

        return mime_to_bytes(message, 0).replace(
            b'\r\n', b'\n').replace(b'\r', b'\n').replace(b'\n', b'\r\n')
    else:
        message_header = ''
        message_body = message.get_payload(decode=True)
        for k, v in message.items():
            message_header += '{}: {}\r\n'.format(k, v)
        message_header += '\r\n'
        return message_header.encode('utf-8') + message_body
180872
def decode_message_headers(msg_headers):
    '''
    
    '''

    headers_to_decode = ['from', 'reply-to', 'subject', 'to']

    for item in headers_to_decode:
        return_list = []
        try:
            # decode the header
            decoded_header = pyzmail_decode_mail_header(msg_headers[item][0])
            # add the header to a list as we want to return a list
            return_list.append(decoded_header)
            # replace the item in the dict with a decoded version
            msg_headers[item] = return_list

        except KeyError:
            pass

    return msg_headers
977600
public function format_message_text($cm, $post) {
        $context = \context_module::instance($cm->id);
        $message = file_rewrite_pluginfile_urls(
            $post->message,
            'pluginfile.php',
            $context->id,
            'mod_forum',
            'post',
            $post->id,
            [
                'includetoken' => true,
            ]);
        $options = new \stdClass();
        $options->para = true;
        $options->context = $context;
        return format_text($message, $post->messageformat, $options);
    }
1370046
protected function _encodeHeader($value)
    {
        if (Zend_Mime::isPrintable($value) === false) {
            if ($this->getHeaderEncoding() === Zend_Mime::ENCODING_QUOTEDPRINTABLE) {
                $value = Zend_Mime::encodeQuotedPrintableHeader($value, $this->getCharset(), Zend_Mime::LINELENGTH, Zend_Mime::LINEEND);
            } else {
                $value = Zend_Mime::encodeBase64Header($value, $this->getCharset(), Zend_Mime::LINELENGTH, Zend_Mime::LINEEND);
            }
        }

        return $value;
    }
1126819
public function buildRawMime($addAllHeaders=true) {
    $mime =  "";
    if (!empty($this->from))
      $mime .=  "From: ".$this->from. "\n";
    if (!empty($this->headers))
      $mime .= $this->headers. "\n";
    if($addAllHeaders){
      // add all headers, even the ones automatically added by the php mail function
      $mime .=  "To: ".$this->to. "\n";
      $subject = $this->subject;
      if ($this->subject_charset) {
        $subject=$this->encodeSubject($subject,$this->subject_charset);
      }
      $mime .=  "Subject: ".$subject. "\n";
    }

    if (!empty($this->body)){
      $this->add_attachment($this->body,  "",  "text/plain");
    }
    // lets build the simpliest message possible
    if (count($this->parts)==1 && count($this->altparts)==0) {
      // single part mail
      $mime .= $this->build_message($this->parts[0]);
    }elseif (count($this->parts)==0 && count($this->altparts)==1) {
      // single part mail
      $mime .= $this->build_message($this->altparts[0]);
    }elseif (count($this->parts)==0 && count($this->altparts)>0) {
      // multi part alternative mail (without attachments)
      $mime .= "MIME-Version: 1.0\n".$this->build_alternative_multipart();
    }else{
      // its a multipart mail with attachments
      $mime .= "MIME-Version: 1.0\n".$this->build_multipart();
    }
    return $mime;
  }
895394
def encode(self, envelope, session, **kwargs):
		
		return WMessengerBytesEnvelope(b64encode(envelope.message()), meta=envelope)