[英]Attachment mail using php mail()?
這是我用來發送帶附件的電子郵件的代碼片段,但它不起作用。我得到的輸出包括大量的哈希碼(我想是這樣)。應該怎么做才能發送screenshot.rar作為附件?
<?php
$to = "abc@gmail.com";
$subject = "A test email";
$random_hash = md5(date('r', time()));
$headers = "From: xyz@gmail.com\r\n";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents("screenshot.rar")));
$output = "
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
--PHP-alt-$random_hash
Content-Type: text/plain; charset='iso-8859-1'
Content-Transfer-Encoding: 7bit
Hello World!
This is the simple text version of the email message.
--PHP-alt-$random_hash
Content-Type: text/html; charset='iso-8859-1'
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is the <b>HTML</b> version of the email message.</p>
--PHP-alt-$random_hash--
--PHP-mixed-$random_hash
Content-Type: application/zip; name=screenshot.rar
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--";
echo @mail($to, $subject, $output, $headers);
?>
PHP Mailer是這個問題的最佳選擇。 試試吧。 點擊這里
例如:
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'jswan'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'from@example.com';
$mail->FromName = 'Mailer';
$mail->AddAddress('josh@example.net', 'Josh Adams'); // Add a recipient
$mail->AddAddress('ellen@example.com'); // Name is optional
$mail->AddReplyTo('info@example.com', 'Information');
$mail->AddCC('cc@example.com');
$mail->AddBCC('bcc@example.com');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->AddAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->AddAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
?>
這是phpmailer提供的示例代碼。
Zend_Mail庫對此非常理想。 庫是精確編寫的,以便在您的情況下,人們不必從頭創建這些包,利用它們。
文檔非常好(上面已鏈接),您只需下載Zend Framework並將其包含在php.ini中的include_files
中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.