Skip to content

Instantly share code, notes, and snippets.

@Criptos
Last active October 25, 2020 18:59
Show Gist options
  • Save Criptos/f093fcb4fca43404049412e49b4c5015 to your computer and use it in GitHub Desktop.
Save Criptos/f093fcb4fca43404049412e49b4c5015 to your computer and use it in GitHub Desktop.
Function to send html mail. It reads the body and converts images to base64 inline attachments. It appends a header and foother. You can also send additional inline attachments via $attachments and it has ical support.
<?php
function sendmail($to, $from $subject, $body, $preheader=false, $attachments=false, $noDom=false, $dstName=false, $url){
$obj = new stdClass();
//Create a new PHPMailer instance
$mail = new PHPMailer;
$msg="";
$mail->SMTPSecure = "tls";
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->Port = "587";
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->AddReplyTo($from);
$mail->setFrom($from, $from);
//Set who the message is to be sent to
if($dstName)
$mail->addAddress($to, $dstName);
else
$mail->addAddress($to);
if(empty($preheader))
$preheader=$subject;
$msg="";
$idx=0;
if(trim($body)!="" && !$noDom ){
$doc=new DOMDocument();
@$doc->loadHTML($body);
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$images=$xml->xpath('//img');
foreach ($images as $img) {
$sourceBase64=$img['src'];
$dataFilename= $img['data-filename'];
$fileName=pathinfo($img['data-filename'], PATHINFO_FILENAME);
$fileExtension=pathinfo($img['data-filename'], PATHINFO_EXTENSION);
if(empty($fileName))
$fileName=uniqid();
if(empty($fileExtension))
$fileExtension="png";
if(preg_match("|data:image/png;base64,|", $sourceBase64)){
$mail->addStringEmbeddedImage(base64_decode(str_replace("data:image/png;base64,", "", $sourceBase64)), "${fileName}_{$idx}", "${fileName}_{$idx}.{$fileExtension}");
$body=str_replace("data:image/png;base64,".$sourceBase64, "cid:${fileName}_{$idx}", $body);
} else {
$mail->addStringEmbeddedImage(file_get_contents($sourceBase64), "${fileName}_{$idx}", "${fileName}_{$idx}.{$fileExtension}");
$body=str_replace($sourceBase64, "cid:${fileName}_{$idx}", $body);
}
}
}
ob_start();
include(dirname(__FILE__)."header.php");
$header=ob_get_contents();
ob_end_clean();
ob_start();
include(dirname(__FILE__)."email.footer.php");
$footer=ob_get_contents();
ob_end_clean();
$msg=$header.$body.$footer;
$mail->Subject = $subject;
$mail->msgHTML($msg);
if(is_array($attachments) && sizeof($attachments)>0)
foreach($attachments as $attach){
if($attach['name']=="ical")
$mail->addStringAttachment($attach['src'],'ical.ics','base64','text/calendar');
else
$mail->addStringAttachment(base64_decode($attach['src']), $attach['name']);
}
if (!$mail->send()) {
$obj->error = __("Message could not be sent")." ". $mail->ErrorInfo;
$obj->code[]=$t['code'];
} else {
$obj->success = __("Message sent");
}
return $obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment