Skip to content

Instantly share code, notes, and snippets.

@KarlBaumann
Created August 19, 2016 14:26
Show Gist options
  • Save KarlBaumann/1f46dbc789b16abda0ba068143ea2420 to your computer and use it in GitHub Desktop.
Save KarlBaumann/1f46dbc789b16abda0ba068143ea2420 to your computer and use it in GitHub Desktop.
<php
protected function prepareHTMLEmail($htmlMessage)
{
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si', $htmlMessage, $matches);
$i = 0;
$paths = [];
// echo $_SERVER['DOCUMENT_ROOT'];
foreach ($matches[1] as $img) {
$img_old = $img;
//replace host name according to current domain alias
$img = makeLinkDynamic($img);
if (strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'] . $uri['path'];
// echo "testpath" . $paths[$i]['path'];
$content_id = md5($img);
$htmlMessage = str_replace($img_old, 'cid:' . $content_id, $htmlMessage);
$paths[$i++]['cid'] = $content_id;
}
}
$boundary = "--" . md5(uniqid(time()));
$header = "MIME-Version: 1.0\n";
$header .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'utf-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: base64\n\n";
$multipart .= chunk_split(base64_encode($htmlMessage)) . "\n\n";
foreach ($paths as $path) {
if (file_exists($path['path'])) {
$fp = fopen($path['path'], "r");
}
if ( ! $fp) {
//return false;
}
$imagetype = substr(strrchr($path['path'], '.'), 1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <' . $path['cid'] . ">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"" . basename($path['path']) . "\"\n\n";
$message_part .= chunk_split(base64_encode($file)) . "\n";
$multipart .= "--$boundary\n" . $message_part . "\n";
}
$multipart .= "--$boundary--\n";
return [
'multipart' => $multipart,
'headers' => $header
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment