string build_alternative_multipart()
Build a build_alternative_multipart mail
515180
private function build_alternative_multipart() {
    $boundary =  "ba".md5(uniqid(time()));

    $multipart =  "Content-Type: multipart/alternative; boundary = $boundary\n\n";

    for($i = sizeof($this->altparts)-1; $i >= 0; $i--)
    {
      $multipart .=  "\n--$boundary\n".$this->build_message($this->altparts[$i]);
    }
    return $multipart.=  "\n--"."$boundary"."--\n";
  }
623126
public function build($alternativeHost = null)
    {
        // Crawl directory and parse all files
        $finder = Util::finder($this->directories, []);
        foreach ($finder as $file) {
            $this->analysis->addAnalysis($this->analyser->fromFile($file->getPathname()));
        }

        // Set alternative host
        $this->analysis->alternativeHost = $alternativeHost;

        // Post processing
        $this->analysis->process($this->processors);

        // Validation (Generate notices & warnings)
        $this->analysis->validate();

        return $this;
    }
646664
public function buildMimeIds($id = null, $rfc822 = false)
    {
        $this->_status &= ~self::STATUS_REINDEX;

        if (is_null($id)) {
            $rfc822 = true;
            $id = '';
        }

        if ($rfc822) {
            if (empty($this->_parts) &&
                ($this->getPrimaryType() != 'multipart')) {
                $this->setMimeId($id . '1');
            } else {
                if (empty($id) && ($this->getType() == 'message/rfc822')) {
                    $this->setMimeId('1.0');
                } else {
                    $this->setMimeId($id . '0');
                }
                $i = 1;
                foreach ($this as $val) {
                    $val->buildMimeIds($id . ($i++));
                }
            }
        } else {
            $this->setMimeId($id);
            $id = $id
                ? ((substr($id, -2) === '.0') ? substr($id, 0, -1) : ($id . '.'))
                : '';

            if (count($this)) {
                if ($this->getType() == 'message/rfc822') {
                    $this->rewind();
                    $this->current()->buildMimeIds($id, true);
                } else {
                    $i = 1;
                    foreach ($this as $val) {
                        $val->buildMimeIds($id . ($i++));
                    }
                }
            }
        }
    }
812669
private Multipart buildContent(Charset charset) throws MessagingException {
		final Multipart mainPart = new MimeMultipart();

		// 正文
		final BodyPart body = new MimeBodyPart();
		body.setContent(content, StrUtil.format("text/{}; charset={}", isHtml ? "html" : "plain", charset));
		mainPart.addBodyPart(body);

		// 附件
		if (ArrayUtil.isNotEmpty(this.attachments)) {
			BodyPart bodyPart;
			for (DataSource attachment : attachments) {
				bodyPart = new MimeBodyPart();
				bodyPart.setDataHandler(new DataHandler(attachment));
				bodyPart.setFileName(InternalMailUtil.encodeText(attachment.getName(), charset));
				mainPart.addBodyPart(bodyPart);
			}
		}

		return mainPart;
	}
975525
public function Build ()
    {

        // Create Boundaries

        $boundary		= '=====' . md5 (uniqid (time ()));

        // Reset headers

        $this->_headers	= array ();

        // Add MIME Headers

        $this->addHeader ('MIME-version: 1.0');
        $this->addHeader ('Content-Type: Multipart/alternative;' . $this->_nl . chr (9) . 'boundary="' . $boundary . '"');

        // Start Message

        $this->_message	= NULL;

        // If there is a template file

        if ($this->_tpl)
        {

            // Load it and add to html

            $this->addHTML (@file_get_contents ($this->_tpl));

        }

        // If HTML data

        if ($this->_htmlSet || $this->_plain)
        {

            // Construct the HTML and add it to the message

            $this->_message	.= $this->constructHTML ($boundary);

        }

        // If Body

        if ($this->_bodySet)
        {

            // Construct the body

            if (!$this->constructBody ())
            {

                // Add error and return FALSE

                new \Sonic\Message ('error', 'Cannot add message body!');
                return FALSE;

            }

        }

        // If Attachments

        if ($this->_attachmentsSet)
        {

            // Add them to the message

            foreach ($this->_attachments as $attachment)
            {
                $this->_message	.= $this->constructAttachment ($attachment, $boundary);
            }

        }

        // Finish Message

        $this->_message	.= '--' . $boundary . '--' . $this->_nl;

        // Return TRUE

        return TRUE;

    }
469362
@Deprecated
    public Postcard build(String path, String group) {
        return _ARouter.getInstance().build(path, group);
    }
412531
def _build_multipart(cls, data):
        
        boundary = b'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
        sep_boundary = b'\n--' + boundary
        end_boundary = sep_boundary + b'--'
        end_items = end_boundary, b"\n",
        builder = functools.partial(
            cls._build_part,
            sep_boundary=sep_boundary,
        )
        part_groups = map(builder, data.items())
        parts = itertools.chain.from_iterable(part_groups)
        body_items = itertools.chain(parts, end_items)
        content_type = 'multipart/form-data; boundary=%s' % boundary.decode('ascii')
        return b''.join(body_items), content_type
1039441
def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None):
        """"""
        if not is_two_file:
            _, data = self.split_metadata(data, None, lang)
        new_data, shortcodes = sc.extract_shortcodes(data)
        # The way pdoc generates output is a bit inflexible
        path_templates = os.path.join(self.plugin_path, "tempaltes")
        LOGGER.info(f"set path tempaltes to {path_templates}")
        with tempfile.TemporaryDirectory() as tmpdir:
            subprocess.check_call(['pdoc', '--html', '--html-no-source', '--html-dir', tmpdir, "--template-dir", path_templates] + shlex.split(new_data.strip()))
            fname = os.listdir(tmpdir)[0]
            tmd_subdir = os.path.join(tmpdir, fname)
            fname = os.listdir(tmd_subdir)[0]
            LOGGER.info(f"tmpdir = {tmd_subdir}, fname = {fname}")
            with open(os.path.join(tmd_subdir, fname), 'r', encoding='utf8') as inf:
                output = inf.read()
        return self.site.apply_shortcodes_uuid(output, shortcodes, filename=source_path, extra_context={'post': post})
1314850
public function getMailMIME()
    {
        $result = '';
        $ismultipart = true;
        switch ($this->message_type) {
            case 'inline':
                $result .= $this->headerLine('Content-Type', 'multipart/related;');
                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
                break;
            case 'attach':
            case 'inline_attach':
            case 'alt_attach':
            case 'alt_inline_attach':
                $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
                break;
            case 'alt':
            case 'alt_inline':
                $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
                break;
            default:
                // Catches case 'plain': and case '':
                $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
                $ismultipart = false;
                break;
        }
        // RFC1341 part 5 says 7bit is assumed if not specified
        if ($this->Encoding != '7bit') {
            // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
            if ($ismultipart) {
                if ($this->Encoding == '8bit') {
                    $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
                }
                // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
            } else {
                $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
            }
        }

        if ($this->Mailer != 'mail') {
            $result .= $this->LE;
        }

        return $result;
    }
1123007
public String buildMailtoContent() {
		StringBuilder sb = new StringBuilder();
		sb.append(email);
		if (StringUtils.isNotEmpty(subject)) {
			sb.append("?").append("subject").append("=").append(subject);
		}
		if (StringUtils.isNotEmpty(body)) {
			sb.append(StringUtils.isNotEmpty(subject) ? "&" : "?").append("body").append("=").append(body);
		}
		return sb.toString().trim();
	}
297331
def construct_mail(self):
        
        # Build body text part. To properly sign/encrypt messages later on, we
        # convert the text to its canonical format (as per RFC 2015).
        canonical_format = self.body.encode('utf-8')
        textpart = MIMEText(canonical_format, 'plain', 'utf-8')

        # wrap it in a multipart container if necessary
        if self.attachments:
            inner_msg = MIMEMultipart()
            inner_msg.attach(textpart)
            # add attachments
            for a in self.attachments:
                inner_msg.attach(a.get_mime_representation())
        else:
            inner_msg = textpart

        if self.sign:
            plaintext = inner_msg.as_bytes(policy=email.policy.SMTP)
            logging.debug('signing plaintext: %s', plaintext)

            try:
                signatures, signature_str = crypto.detached_signature_for(
                    plaintext, [self.sign_key])
                if len(signatures) != 1:
                    raise GPGProblem("Could not sign message (GPGME "
                                     "did not return a signature)",
                                     code=GPGCode.KEY_CANNOT_SIGN)
            except gpg.errors.GPGMEError as e:
                if e.getcode() == gpg.errors.BAD_PASSPHRASE:
                    # If GPG_AGENT_INFO is unset or empty, the user just does
                    # not have gpg-agent running (properly).
                    if os.environ.get('GPG_AGENT_INFO', '').strip() == '':
                        msg = "Got invalid passphrase and GPG_AGENT_INFO\
                                not set. Please set up gpg-agent."
                        raise GPGProblem(msg, code=GPGCode.BAD_PASSPHRASE)
                    else:
                        raise GPGProblem("Bad passphrase. Is gpg-agent "
                                         "running?",
                                         code=GPGCode.BAD_PASSPHRASE)
                raise GPGProblem(str(e), code=GPGCode.KEY_CANNOT_SIGN)

            micalg = crypto.RFC3156_micalg_from_algo(signatures[0].hash_algo)
            unencrypted_msg = MIMEMultipart(
                'signed', micalg=micalg, protocol='application/pgp-signature')

            # wrap signature in MIMEcontainter
            stype = 'pgp-signature; name="signature.asc"'
            signature_mime = MIMEApplication(
                _data=signature_str.decode('ascii'),
                _subtype=stype,
                _encoder=encode_7or8bit)
            signature_mime['Content-Description'] = 'signature'
            signature_mime.set_charset('us-ascii')

            # add signed message and signature to outer message
            unencrypted_msg.attach(inner_msg)
            unencrypted_msg.attach(signature_mime)
            unencrypted_msg['Content-Disposition'] = 'inline'
        else:
            unencrypted_msg = inner_msg

        if self.encrypt:
            plaintext = unencrypted_msg.as_bytes(policy=email.policy.SMTP)
            logging.debug('encrypting plaintext: %s', plaintext)

            try:
                encrypted_str = crypto.encrypt(
                    plaintext, list(self.encrypt_keys.values()))
            except gpg.errors.GPGMEError as e:
                raise GPGProblem(str(e), code=GPGCode.KEY_CANNOT_ENCRYPT)

            outer_msg = MIMEMultipart('encrypted',
                                      protocol='application/pgp-encrypted')

            version_str = 'Version: 1'
            encryption_mime = MIMEApplication(_data=version_str,
                                              _subtype='pgp-encrypted',
                                              _encoder=encode_7or8bit)
            encryption_mime.set_charset('us-ascii')

            encrypted_mime = MIMEApplication(
                _data=encrypted_str.decode('ascii'),
                _subtype='octet-stream',
                _encoder=encode_7or8bit)
            encrypted_mime.set_charset('us-ascii')
            outer_msg.attach(encryption_mime)
            outer_msg.attach(encrypted_mime)

        else:
            outer_msg = unencrypted_msg

        headers = self.headers.copy()
        # add Message-ID
        if 'Message-ID' not in headers:
            headers['Message-ID'] = [email.utils.make_msgid()]

        if 'User-Agent' in headers:
            uastring_format = headers['User-Agent'][0]
        else:
            uastring_format = settings.get('user_agent').strip()
        uastring = uastring_format.format(version=__version__)
        if uastring:
            headers['User-Agent'] = [uastring]

        # copy headers from envelope to mail
        for k, vlist in headers.items():
            for v in vlist:
                outer_msg.add_header(k, v)

        return outer_msg
1060304
def string_build(self, data, modname="", path=None):
        """"""
        module = self._data_build(data, modname, path)
        module.file_bytes = data.encode("utf-8")
        return self._post_build(module, "utf-8")
739197
def multipart(body, content_length=0, **header_params):
    """"""
    header_params.setdefault('CONTENT-LENGTH', content_length)
    if header_params and 'boundary' in header_params:
        if type(header_params['boundary']) is str:
            header_params['boundary'] = header_params['boundary'].encode()

    form = parse_multipart((body.stream if hasattr(body, 'stream') else body), header_params)
    for key, value in form.items():
        if type(value) is list and len(value) is 1:
            form[key] = value[0]
    return form
593184
protected function buildEmail()
    {
        $email = $this->getEmailObject();

        $email->setSubject($this->getSubject());
        $email->setRecipient($this->getRecipient());
        $email->setFrom($this->getSender());
        $email->setBody($this->getBody());

        return $email;
    }
771894
function build($url,$params=array()) {
		$params+=$this->hive['PARAMS'];
		if (is_array($url))
			foreach ($url as &$var) {
				$var=$this->build($var,$params);
				unset($var);
			}
		else {
			$i=0;
			$url=preg_replace_callback('/@(\w+)|\*/',
				function($match) use(&$i,$params) {
					$i++;
					if (isset($match[1]) &&
						array_key_exists($match[1],$params))
						return $params[$match[1]];
					return array_key_exists($i,$params)?
						$params[$i]:
						$match[0];
				},$url);
		}
		return $url;
	}
1317295
def attach_alternative(self, content, mimetype=None):
        """"""
        self.attach(content=content, mimetype=mimetype)
408594
protected function build()
    {
        $mail = clone $this;
        $mail->setHeader('Message-ID', $this->getRandomId());

        $cursor = $mail;
        if ($mail->attachments) {
            $tmp = $cursor->setContentType('multipart/mixed');
            $cursor = $cursor->addPart();
            foreach ($mail->attachments as $value) {
                $tmp->addPart($value);
            }
        }

        if ($mail->htmlBody !== '') {
            $tmp = $cursor->setContentType('multipart/alternative');
            $cursor = $cursor->addPart();
            $alt = $tmp->addPart();
            if ($mail->inlines) {
                $tmp = $alt->setContentType('multipart/related');
                $alt = $alt->addPart();
                foreach ($mail->inlines as $value) {
                    $tmp->addPart($value);
                }
            }
            $alt->setContentType('text/html', 'UTF-8')
                ->setEncoding(\preg_match('#[^\n]{990}#', $mail->htmlBody)
                    ? self::ENCODING_QUOTED_PRINTABLE
                    : (\preg_match('#[\x80-\xFF]#', $mail->htmlBody) ? self::ENCODING_8BIT : self::ENCODING_7BIT))
                ->setBody($mail->htmlBody);
        }

        $text = $mail->getBody();
        $mail->setBody('');
        $cursor->setContentType('text/plain', 'UTF-8')
            ->setEncoding(\preg_match('#[^\n]{990}#', $text)
                ? self::ENCODING_QUOTED_PRINTABLE
                : (\preg_match('#[\x80-\xFF]#', $text) ? self::ENCODING_8BIT : self::ENCODING_7BIT))
            ->setBody($text);

        return $mail;
    }