Outputs an encoded string representation of the mail message including
 all headers, attachments, etc.  This is an encoded email in US-ASCII,
 so it is able to be directly sent to an email server.
971884
def encoded
      ready_to_send!
      buffer = header.encoded
      buffer << "\r\n"
      buffer << body.encoded(content_transfer_encoding)
      buffer
    end
1072718
def encode_string(data, encoding='hex'):
    '''
    
    '''
    if six.PY2:
        return data.encode(encoding)
    else:
        if isinstance(data, str):
            data = bytes(data, 'utf-8')
        return codecs.encode(data, encoding).decode('ascii')
941
String
rrToString() {
	StringBuffer sb = new StringBuffer();
	sb.append(mailbox);
	sb.append(" ");
	sb.append(textDomain);
	return sb.toString();
}
519041
def fetch_email(M, msg_id):
    """"""
    res, data = M.fetch(msg_id, '(RFC822)')
    if res == 'OK':
        # Data here is a list with 1 element containing a tuple
        # whose 2nd element is a long string containing the email
        # The content is a bytes that must be decoded
        raw_msg_txt = data[0][1]
        # In Python3, we call message_from_bytes, but this function doesn't
        # exist in Python 2.
        try:
            msg = email.message_from_bytes(raw_msg_txt)
        except AttributeError:
            msg = email.message_from_string(raw_msg_txt)
        # At this point, we have a message containing bytes (not unicode)
        # fields that will still need to be decoded, ideally according to the
        # character set specified in the message.
        return msg
    else:
        return None
875553
def mail_partial_json(self):
        
        if self.mail_partial.get("date"):
            self._mail_partial["date"] = self.date.isoformat()
        return json.dumps(self.mail_partial, ensure_ascii=False, indent=2)
949510
def get_encoding_from_headers(headers):
    

    content_type = headers.get('content-type')

    if not content_type:
        return None

    content_type, params = _parse_content_type_header(content_type)

    if 'charset' in params:
        return params['charset'].strip("'\"")

    if 'text' in content_type:
        return 'ISO-8859-1'
544683
protected function buildEmailString()
    {
        $email = $this->prefix.$this->email;

        if (isset($this->subject) || isset($this->body)) {
            $data = [
                'subject' => $this->subject,
                'body'    => $this->body,
            ];
            $email .= '?'.http_build_query($data);
        }

        return $email;
    }
1096175
def string(self) -> bytes:
        """"""
        if self._raw is not None:
            return self._raw
        self._raw = raw = BytesFormat(b' ').join(
            [b'CAPABILITY', b'IMAP4rev1'] + self.capabilities)
        return raw
259648
def send_mail(subject, text_content, from_email, to, html_content=None, attachments=[], cc=[], bcc=[]):
    
    msg = EmailMultiAlternatives(subject, text_content, from_email, to, cc=cc, bcc=bcc)
    if html_content:
        msg.attach_alternative(html_content, "text/html")
    if attachments:
        for att in attachments:
            if att:

                mimetype = mimetypes.guess_type(att)[0]
                if str(mimetype) in ('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'):
                    try:
                        with open(att, 'r') as f:
                            email_embed_image(msg, att, f.read())
                    except Exception as e:
                        print(e)
                else:
                    msg.attach_file(att)
    return msg.send()
3348
public String getDecodedMessage()
    {
        if (message == null)
        {
            return null;
        }
        return new String(Base64.base64ToByteArray(message), Charset.forName("UTF-8"));
    }
214352
function encodeEmailwithSubject($email, $name = null, $sujet="")
    {
        $email = preg_replace("/\"/", "\\\"", $email);

        if ($name == null) {
            $name = $email;
        }

        $old1 = "document.write('<a class=lien href=\"mailto:$email?subject=";
        //".$sujet."
        $old2= "\">$name</a>')";



        $output1 = "";

        for ($i=0; $i < pia_strlen($old1); $i++) {
            $output1 = $output1 . '%' . bin2hex(pia_substr($old1, $i, 1));
        }

        $output2 = "";

        for ($i=0; $i<pia_strlen($old2); $i++) {
            $output2 = $output2 .'%'.bin2hex(pia_substr($old2, $i, 1));
        }


        $output="";
        $output = '<script type="text/javascript">eval(unescape(\''.
            $output1.'\')+"'.$sujet.'"+unescape(\''.$output2.'\'))</script>';
        $output .= '<noscript><div>Vous devez accepter le Javascript'.
            ' pour voir l\'email</div></noscript>';
        return $output;
    }
1009801
protected function decodeBody()
    {
        if(is_object($this->message)){
            foreach ($this->message->types as $typeMessage) {
                if(is_object($this->message->$typeMessage)){
                    switch ($this->message->$typeMessage->structure->encoding) {
                        case 3:
                            $this->message->$typeMessage->body = imap_base64($this->message->$typeMessage->body);
                            break;
                        case 4:
                            $this->message->$typeMessage->body = imap_qprint($this->message->$typeMessage->body);
                            break;
                    }
                }

                if(is_object($this->message->$typeMessage)){
                    if ($this->message->$typeMessage->charset) {
                        $this->message->$typeMessage->body = $this->convertToUtf8($this->message->$typeMessage->body, $this->message->$typeMessage->charset);
                    }
                }
            }
        }
    }
1135482
public static function encodeEmail(string $email) : string
    {
        return md5(self::EMAIL_PREF . preg_replace('/\\s/', '', mb_strtolower($email)) . self::EMAIL_SUFF);
    }
374011
def prepare_message(user, useralias, addresses, subject, contents, attachments, headers, encoding, newline_to_break=True):
    # check if closed!!!!!! XXX
    
    if isinstance(contents, text_type):
        contents = [contents]
    if isinstance(attachments, text_type):
        attachments = [attachments]

    # merge contents and attachments for now.
    if attachments is not None:
        for a in attachments:
            if not os.path.isfile(a):
                raise TypeError("'{0}' is not a valid filepath".format(a))
        contents = attachments if contents is None else contents + attachments

    has_included_images, content_objects = prepare_contents(contents, encoding)
    msg = MIMEMultipart()
    if headers is not None:
        # Strangely, msg does not have an update method, so then manually.
        for k, v in headers.items():
            msg[k] = v
    if headers is None or "Date" not in headers:
        msg["Date"] = formatdate()

    msg_alternative = MIMEMultipart("alternative")
    msg_related = MIMEMultipart("related")
    msg_related.attach("-- HTML goes here --")
    msg.attach(msg_alternative)
    add_subject(msg, subject)
    add_recipients_headers(user, useralias, msg, addresses)
    htmlstr = ""
    altstr = []
    if has_included_images:
        msg.preamble = "This message is best displayed using a MIME capable email reader."

    if contents is not None:
        for content_object, content_string in zip(content_objects, contents):
            if content_object["main_type"] == "image":
                # all image objects need base64 encoding, so do it now
                email.encoders.encode_base64(content_object["mime_object"])
                # aliased image {'path' : 'alias'}
                if isinstance(content_string, dict) and len(content_string) == 1:
                    for key in content_string:
                        hashed_ref = str(abs(hash(key)))
                        alias = content_string[key]
                    # pylint: disable=undefined-loop-variable
                    content_string = key
                else:
                    alias = os.path.basename(str(content_string))
                    hashed_ref = str(abs(hash(alias)))

                # TODO: I should probably remove inline now that there is "attachments"
                # if string is `inline`, inline, else, attach
                # pylint: disable=unidiomatic-typecheck
                if type(content_string) == inline:
                    htmlstr += '<img src="cid:{0}" title="{1}"/>'.format(hashed_ref, alias)
                    content_object["mime_object"].add_header(
                        "Content-ID", "<{0}>".format(hashed_ref)
                    )
                    altstr.append("-- img {0} should be here -- ".format(alias))
                    # inline images should be in related MIME block
                    msg_related.attach(content_object["mime_object"])
                else:
                    # non-inline images get attached like any other attachment
                    msg.attach(content_object["mime_object"])

            else:
                if content_object["encoding"] == "base64":
                    email.encoders.encode_base64(content_object["mime_object"])
                    msg.attach(content_object["mime_object"])
                elif content_object["sub_type"] not in ["html", "plain"]:
                    msg.attach(content_object["mime_object"])
                else:
                    if newline_to_break:
                        content_string = content_string.replace("\n", "<br>")
                    try:
                        htmlstr += "<div>{0}</div>".format(content_string)
                    except UnicodeEncodeError:
                        htmlstr += u"<div>{0}</div>".format(content_string)
                    altstr.append(content_string)

    msg_related.get_payload()[0] = MIMEText(htmlstr, "html", _charset=encoding)
    msg_alternative.attach(MIMEText("\n".join(altstr), _charset=encoding))
    msg_alternative.attach(msg_related)
    return msg
1115816
def get_smtp_header(self):
        
        header = "From: %s\r\n" % self.get_sender()
        header += "To: %s\r\n" % ',\r\n '.join(self.get_to())
        header += "Cc: %s\r\n" % ',\r\n '.join(self.get_cc())
        header += "Bcc: %s\r\n" % ',\r\n '.join(self.get_bcc())
        header += "Subject: %s\r\n" % self.get_subject()
        return header
488290
def message(self):
        
        return '\n'.join(
            [self.from_email, str(self.to), self.subject, self.body])
938422
protected function decodeAttachments()
    {
        foreach ($this->attachments as $key => $attachment) {
            /*
             * Decode body
             */
            switch ($attachment->info->structure->encoding) {
                case 3:
                    $this->attachments[$key]->body = imap_base64($attachment->body);
                    break;
                case 4:
                    $this->attachments[$key]->body = quoted_printable_decode($attachment->body);
                    break;
            }
            /*
             * Decode name
             */
            $this->attachments[$key]->name = $this->mimeHeaderDecode($attachment->name);
        }
    }