網頁

2013年4月29日

[php] 使用mail寄送檔案及嵌入圖片

程式範例:
<?php
//設定時區
date_default_timezone_set("Asia/Taipei");
//建立唯一ID
$id = sha1(date('r', time()));
//收件者郵件地址 (收件者、副本、密本)
$to = array();
$to[] = "you@domain";
$to[] = "he@domain";
$to[] = "she@domain";
//信件標題 (中文字必須使用mime編碼)
$subject = "=?utf-8?B?".base64_encode("這是測試夾檔的信件!")."?=";

//信件檔頭 (mime格式)
$headers = "\r\nContent-Type: multipart/mixed;
boundary=\"PHP-mixed-".$id."\"";
//收件者 (中文字必須使用mime編碼,可參考信件標題的寫法)
$headers .= "To: You <you@domain>\r\n";
//寄件者
$headers .= "From: Me <me@you@domain>\r\n";
//副本(可省略)
$headers .= "Cc: he@domain\r\n";
//密本(可省略)
$headers .= "Bcc: she@domain\r\n";
//夾帶檔案
$attached = chunk_split(base64_encode(file_get_contents("attachment.zip")));
//嵌入圖檔
$inline = chunk_split(base64_encode(file_get_contents("picture.gif")));
//信件內容
$body ="EOBODY
--PHP-mixed-".$id." Content-Type: multipart/alternative; boundary=\"PHP-alt-".$id."\"
--PHP-alt-".$id." Content-Type: text/plain
嗨~這裡是純文字的內容!

--PHP-alt-".$id." Content-Type: multipart/related; boundary=\"PHP-related-".$id."\"
--PHP-alt-".$id." Content-Type: text/html
< html>
< head>
< title>信件測試</title>
< /head>
< body>
< h1>嗨~這裡是HTML的內容!</h1><br />
這是嵌入式圖片:
<img src=\"cid:PHP-CID-".$id."\" />
< /body>
< /html>
--PHP-related-".$id."
Content-Type: image/gif
Content-Transfer-Encoding: base64
Content-ID: <PHP-CID-".$id.">
".$inline."
--PHP-related-".$id."--
--PHP-alt-".$id."--
--PHP-mixed-".$id."
Content-Type: application/zip; name=\"attachment.zip\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
".$attached."

--PHP-mixed-".$id."--
EOBODY;";
//寄信
mail(implode(",", $to), $subject, $body, $headers);
?>