wppaste
WordPress

PHPMailer::msgHTML( string $message, string $basedir = '', bool|callable $advanced = false ): string

Source
wp-includes/PHPMailer/PHPMailer.php:4721
Create a message body from an HTML string.

Description

Automatically inlines images and creates a plain-text version by converting the HTML, overwriting any existing values in Body and AltBody.
Do not source $message content from user input! $basedir is prepended when handling relative URLs, e.g. and must not be empty will look for an image file in $basedir/images/a.png and convert it to inline.
If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) Converts data-uri images into embedded attachments.
If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.

Compatibility

WordPress
core
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$messagestring
HTML message string
$basedirstringoptional
Absolute path to a base directory to prepend to relative paths to imagesDefault: ''
$advancedbool|callableoptional
Whether to use the internal HTML to text converter or your own custom converterDefault: false

Return value

string
The transformed message body

Performance profile

How much work a call to PHPMailer::msgHTML() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Light

Touches nothing outside its own arguments.

Scaling
Scales with input

The body loops, so the work grows with what you pass in.

Instructions
38–62

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 207.

Plugin surface
None

Nothing here hands control to plugin code.

Called by
0

Nothing in core calls this; the cost is only what you spend yourself.

What it touches

  • regexregular expression over the whole inputpreg_match_all()called directly

What one call costs · 2 distinct outcomes

One number would be a lie: the work depends on which branch runs. These are every distinct cost PHPMailer::msgHTML() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
!filter_var()38–53filter_var(), preg_match_all(), ->isHTML(), ::normalizeBreaks(), ->html2text(), ::normalizeBreaks(), ->alternativeExists()
filter_var()47–62filter_var(), strrpos(), preg_match_all(), ->isHTML(), ::normalizeBreaks(), ->html2text(), ::normalizeBreaks(), ->alternativeExists()

Across PHP versions

PHPCompiledExecutedBranchesNotes
8.6-dev20738–6222
8.520738–6222
8.420738–622235 fewer instructions than PHP 8.3
8.324238–6822
8.224238–6822
8.124238–6822
7.424238–6822

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Uses · 9

  • \PHPMailer\PHPMailer\PHPMailer::cidExists()
  • \PHPMailer\PHPMailer\PHPMailer::addStringEmbeddedImage()
  • static::mb_pathinfo()
  • \PHPMailer\PHPMailer\PHPMailer::addEmbeddedImage()
  • static::_mime_types()
  • \PHPMailer\PHPMailer\PHPMailer::isHTML()
  • static::normalizeBreaks()
  • \PHPMailer\PHPMailer\PHPMailer::html2text()
  • \PHPMailer\PHPMailer\PHPMailer::alternativeExists()

Source code

    public function msgHTML($message, $basedir = '', $advanced = false)    {        $cid_domain = 'phpmailer.0';        if (filter_var($this->From, FILTER_VALIDATE_EMAIL)) {            //prepend with a character to create valid RFC822 string in order to validate            $cid_domain = substr($this->From, strrpos($this->From, '@') + 1);        }         preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);        if (array_key_exists(2, $images)) {            if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {                //Ensure $basedir has a trailing /                $basedir .= '/';            }            foreach ($images[2] as $imgindex => $url) {                //Convert data URIs into embedded images                //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="                $match = [];                if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {                    if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) {                        $data = base64_decode($match[3]);                    } elseif ('' === $match[2]) {                        $data = rawurldecode($match[3]);                    } else {                        //Not recognised so leave it alone                        continue;                    }                    //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places                    //will only be embedded once, even if it used a different encoding                    $cid = substr(hash('sha256', $data), 0, 32) . '@' . $cid_domain; //RFC2392 S 2                     if (!$this->cidExists($cid)) {                        $this->addStringEmbeddedImage(                            $data,                            $cid,                            'embed' . $imgindex,                            static::ENCODING_BASE64,                            $match[1]                        );                    }                    $message = str_replace(                        $images[0][$imgindex],                        $images[1][$imgindex] . '="cid:' . $cid . '"',                        $message                    );                    continue;                }                if (                    //Only process relative URLs if a basedir is provided (i.e. no absolute local paths)                    !empty($basedir)                    //Ignore URLs containing parent dir traversal (..)                    && (strpos($url, '..') === false)                    //Do not change urls that are already inline images                    && 0 !== strpos($url, 'cid:')                    //Do not change absolute URLs, including anonymous protocol                    && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)                ) {                    $filename = static::mb_pathinfo($url, PATHINFO_BASENAME);                    $directory = dirname($url);                    if ('.' === $directory) {                        $directory = '';                    }                    //RFC2392 S 2                    $cid = substr(hash('sha256', $url), 0, 32) . '@' . $cid_domain;                    if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {                        $basedir .= '/';                    }                    if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {                        $directory .= '/';                    }                    if (                        $this->addEmbeddedImage(                            $basedir . $directory . $filename,                            $cid,                            $filename,                            static::ENCODING_BASE64,                            static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))                        )                    ) {                        $message = preg_replace(

Changelog

Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

About this page

Parsed data
Generated from the wordpress-develop 7.1.0 tag, from src/wp-includes/PHPMailer/PHPMailer.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.