我有一個PHP腳本,它會發送帶有附加圖像的HTML電子郵件。它工作得很好,但是,我無法將附件顯示在電子郵件正文的<img>
標記中。附件名爲postcard.png
,服務器上的原始文件名爲4e60348f83f2f.png
。我已經嘗試將圖片網址設置爲各種東西:cid:postcard.png
,cid:4e60348f83f2f.png
,postcard.png
和4e60348f83f2f.png
。什麼都沒有如何發送HTML電子郵件,並附帶內聯PHP圖像
我認爲我做錯了的關鍵部分是在這裏,因爲這使得分離附件,而不是內嵌附件,我可以使用:
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="$fname" // i.e.: "postcard.png"
我試圖將其更改爲使用一個CID,但我真的不知道該怎麼做,這didnt」在所有的工作:
Content-Transfer-Encoding: base64
Content-ID: <$fname> // i.e.: postcard.png
下面是完整的代碼:(它是基於this code從PHP mail()
頁的註釋。)
<?php
$to = "[email protected]";
$email = "[email protected]";
$name = "Namename";
$subject = "An inline image!";
$comment = "Llookout <b>Llary</b> it's <br> the <b>Ll</b>andllord!<br><img src='cid:postcard.png'><br><img src='cid:4e60348f83f2f.png'><img src='postcard.png'><br><img src='4e60348f83f2f.png'>";
$To = strip_tags($to);
$TextMessage =strip_tags(nl2br($comment),"<br>");
$HTMLMessage =nl2br($comment);
$FromName =strip_tags($name);
$FromEmail =strip_tags($email);
$Subject =strip_tags($subject);
$boundary1 =rand(0,9)."-"
.rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
$boundary2 =rand(0,9)."-".rand(10000000000,9999999999)."-"
.rand(10000000000,9999999999)."=:"
.rand(10000,99999);
$filename1 = "4e60348f83f2f.png"; //name of file on server with script
$handle =fopen($filename1, 'rb');
$f_contents =fread($handle, filesize($filename1));
$attachment=chunk_split(base64_encode($f_contents));
fclose($handle);
$ftype ="image/png";
$fname ="postcard.png"; //what the file will be named
$attachments='';
$Headers =<<<AKAM
From: $FromName <$FromEmail>
Reply-To: $FromEmail
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="$boundary1"
AKAM;
$attachments.=<<<ATTA
--$boundary1
Content-Type: $ftype;
name="$fname"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="$fname"
$attachment
ATTA;
$Body =<<<AKAM
This is a multi-part message in MIME format.
--$boundary1
Content-Type: multipart/alternative;
boundary="$boundary2"
--$boundary2
Content-Type: text/plain;
charset="windows-1256"
Content-Transfer-Encoding: quoted-printable
$TextMessage
--$boundary2
Content-Type: text/html;
charset="windows-1256"
Content-Transfer-Encoding: quoted-printable
$HTMLMessage
--$boundary2--
$attachments
--$boundary1--
AKAM;
// Send email
$ok=mail($To, $Subject, $Body, $Headers);
echo $ok?"<h1> Mail sent!</h1>":"<h1> Mail not sent!</h1>";
?>
使用[PHPMailer](http://phpmailer.worxware.com)或[Swiftmailer](http://swiftmailer.org)。兩者都允許內聯附件完全無任何痛苦,這與您從頭開始構建MIME郵件的過程不同。 –
這並不是說不可能手工完成,但使用Swiftmailer或PHPMailer將不會太麻煩。 - 可能重複[發送電子郵件與PHPMailer - 嵌入圖像在正文](http://stackoverflow.com/questions/3708153/send-email-with-phpmailer-embed-image-in-body) – mario
@Marc乙:我不知道,我用PHPMailer輸入了一次hangig,這有點痛苦。 –