我有一个非常漂亮的HTML模板,我现在需要实现到我的邮件系统。我现在用这个来发送电子邮件:
$to = $dbuser;
$subject = "Welcome";
$from = "support@mysite.com";
$headers = "From: $from";
$server = "";
ini_set ("SMTP", $localhost);
$url="";
$msg="$url";
$body = Example Text!
mail($to, $subject, $body, $headers);
我如何包括一个HTML模板(沿着CSS)直接到我的php电子邮件表单的$body变量?
我做了不少研究,但找不到任何实质性的。
您缺少电子邮件客户端将消息解释为HTML所需的标题。在标题中添加以下内容:
$headers = "From: " . $from . "'r'n";
$headers .= "MIME-Version: 1.0" . "'r'n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "'r'n";
我过去使用过的一种方法是像通常那样创建页面(使用html/php等),然后使用file_get_contents($url),如下所示:
$body = file_get_contents("http://mydomain.com/emailtemplates/template.php?name=John Doe&subject=Hello");
因为您使用的是http://, php被执行而不是拉入模板,简单但有效!
我也会建议你使用内联css,不要害怕使用表格!
http://php.net/manual/en/function.mail.php -示例#5
还要记住,在HTML电子邮件中,强烈建议您尽可能使用内联CSS和老式HTML格式,以确保与不同的电子邮件客户端最大程度地兼容。也没有divs
,只有普通的老table
-s
首先,您需要添加一些标题,以便正确显示HTML。从mail() PHP文档中获取,您可以这样做:
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "'r'n";
之后,我假设$body是文本应该在的地方,所以这是一个将所有HTML放在引号之间的问题(用反斜杠转义HTML中的每个引号),这几乎就是它。
我昨天为自己写了这个:
- 创建你的html并把它放在一个名为"./email.html"的文件中
- 将下面的代码粘贴到与html文件相同目录下的php文件中。
- 修改图片名称,如果你在HTML中使用他们只是这样做:src="cid:world.jpg"
就是这样……我认为。=)
//attachment file paths/names
$files[0] = './world.jpg';
$files[1] = './world2.jpg';
$to = '';
$bcc = "";
$subject = '';
$from = "";
$htmlx = '';
$handle = @fopen("./email.html", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$htmlx .= $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail'n";
}
fclose($handle);
}
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x".$semi_rand."x";
$headers = "From: $from 'n";
$headers .= "Reply-To: $from 'n";
$headers .= 'Bcc: '. $bcc . "'n";
$headers .= "MIME-Version: 1.0'n" . "Content-Type: multipart/mixed;'n" . ' boundary="'.$mime_boundary.'"'."'n";
$headers .= "X-Author: <Timothy Martens>'n";
$message = '--'.$mime_boundary."'n";
$message .= 'Content-Type: text/html; charset=UTF-8'."'n";
$message .= "Content-Transfer-Encoding: 7bit'n'n'n". $htmlx . "'n'n'n";
// preparing attachments
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--".$mime_boundary."'n";
$fp = @fopen($files[$i],"rb");
$data = @fread($fp,filesize($files[$i]));
@fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name='"".basename($files[$i])."'"'n" .
"Content-Description: ".basename($files[$i])."'n" .
"Content-ID: <".basename($files[$i]).">'n".
"Content-Disposition: attachment;'n" . " filename='"".basename($files[$i])."'"; size=".filesize($files[$i]).";'n" .
"Content-Transfer-Encoding: base64'n'n" . $data . "'n'n";
}
}
$message .= "--".$mime_boundary."--";
if (mail($to, $subject, $message, $headers)) {
echo 'Your message has been sent.'."'n";
} else {
echo 'There was a problem sending the email.'."'n";
}