我試圖設置一個Web應用程序,完成後向具有附件的用戶發送電子郵件。我希望電子郵件既可以使用HTML格式,也可以使用文本格式,以確保每個人都可以查看它,而不管他們的郵件設置如何。我無法正常工作,所以我想知道是否有人可以用我的代碼發現問題。帶附件的HTML /文本電子郵件使用PHP
我使用的代碼如下。這被作爲另一個網站的模板,但我已經做了大量的閱讀,所以我粗略瞭解它是如何工作的。不幸的是,沒有足夠的理解來解決問題!
$firstname = $_POST['firstname'];
$email = $_POST['email'];
//define the receiver of the email
$to = $email;
//define the subject of the email
$subject = "$firstname, thanks for using the One Minute Leveller";
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: The Xenon Group\r\nReply-To: [email protected]";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('Level3info.pdf')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
TEXT E-MAIL GOES HERE. ACTUAL CONTENT REMOVED
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<html><h1>HTML CONTENT GOES HERE. ACTUAL CONTENT REMOVED</h1></html>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/pdf; name="Level3info.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
mail($to, $subject, $message, $headers);
任何人都可以幫忙嗎?
我會建議不要像這樣跳出和跳出PHP。它使你的代碼難以閱讀。 – Travesty3 2012-01-31 15:30:23
我強烈建議使用現有的類來完成這樣的任務!見http://pear.php.net/manual/en/package.mail.mail-mime.addattachment.php – powtac 2012-01-31 15:31:51