PHP Attach PDF mail function

余生颓废 提交于 2019-12-04 16:45:50

I would move your antispam check up to the top, but I got the code below to work. I changed your EOL tag to "\r\n" and also added another $eol at the end of the header. Also I changed $message to $body in the mail() call, as all the prep work was done for $body but it wasn't used.

// a random hash will be necessary to send mixed content
$separator = md5(time());

// carriage return type (we use a PHP end of line constant)
$eol = "\r\n";

// attachment name
$filename = "test.txt";

// encode data (puts attachment in proper format)
$attachment = chunk_split(base64_encode("I am text file"));

// main header
$headers  = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol; 
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol;

// no more headers after this, we start the body! //
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;

// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;

// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol; 
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";

// form values
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$postcode = md5($_POST['post']);
$email = $_POST['email'];


echo mail($to, $subject, $body, $headers) or die("Mail Error");                   
echo "<p>Voucher has been emailed, we looked foward to seeing you soon</p>\n";

I have a mail class written. The attachment code is like:

$body .= "--".$separator."\r\n";
$body .= "Content-Disposition: attachment; filename=\"".$filename."\";\r\n";
$body .= "Content-Length: ".$filesize.";\r\n";
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= $attachment."\r\n";
$body .= "--".$separator."--";

You see some differences: I've Content-Length, 2x $filename and \r\n as EOL.

I hope this helps.

There are so many possible break-points in this code, it's impossible to tell exactly what goes wrong. You'll need to do some debugging on your own, eg. using test outputs, to see how far the script gets. Also make sure you activate error reporting.

To send attachments an easier way might be using the SwiftMailer library.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!