отправить письмо с вложением в формате PDF - PullRequest
6 голосов
/ 20 июля 2011

Я пытаюсь отправить электронное письмо с помощью функции mail() в php с вложением в формате pdf. Я запускаю сценарий на локальной машине. Я установил SMTP IP в php.ini. Я могу отправить текстовое электронное письмо отлично, но с вложением я получаю следующую ошибку:

Warning: mail() [function.mail]: SMTP server response: 503 Unexpected command or sequence of commands in C:\AppServ\www\PhpProject1\CV-Generator\testemail2.php on line 55

Может кто-нибудь сказать мне, что не так, пожалуйста?

Вот мой код:

<?php
// download fpdf class (http://fpdf.org)
require('./pdf/fpdf.php');

// fpdf object
$pdf = new FPDF();

// generate a simple PDF (for more info, see http://fpdf.org/en/tutorial/)
$pdf->AddPage();
$pdf->SetFont("Arial","B",14);
$pdf->Cell(40,10, "this is a pdf example");

// email stuff (change data below)
$to = $_GET['send']; 
$from = "info@asaltechd.com"; 
$subject = "send email with pdf attachment"; 
$message = "<p>Please see the attachment.</p>";

// 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 = PHP_EOL;

// attachment name
$filename = "example.pdf";

// encode data (puts attachment in proper format)
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));


// main header (multipart mandatory)
$headers  = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol; 
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol; 
$headers .= "Content-Transfer-Encoding: 7bit".$eol;
$headers .= "This is a MIME encoded message.".$eol.$eol;

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

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

// send message
mail($to, $subject, "", $headers);

?>

Ответы [ 3 ]

7 голосов
/ 20 июля 2011

Я использую PHP SwiftMailer (http://swiftmailer.org/):

require_once('../lib/swiftMailer/lib/swift_required.php');

...


$body="Dear $fname,\n\nPlease find attached, an invoice for the period $startDate - $endDate\n\nBest regards,\n\nMr X";

$message = Swift_Message::newInstance('Subject goes here')
    ->setFrom(array($email => "no-reply@mydomain.com"))
    ->setTo(array($email => "$fname $lname"))
    ->setBody($body);
$message->attach(Swift_Attachment::fromPath("../../invoices_unpaid/$id.pdf"));

$result = $mailer->send($message);
7 голосов
/ 20 июля 2011

Вложение не входит в заголовки!Они должны объявлять только заголовки MIME:

// main header (multipart mandatory)
$headers  = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol; 
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol; // see below 
$headers .= "Content-Transfer-Encoding: 7bit".$eol;


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

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

// send message
mail($to, $subject, $msg, $headers);

Обратите внимание, что вы НИКОГДА не должны иметь 2 последовательных конца строки в заголовках - SMTP использует пустую строку в качестве разделителя между заголовками и телом.

Кроме того, EOL НЕ должно быть значением по умолчанию в вашей операционной системе - это должна быть последовательность EOL, как определено SMTP - то есть CR + LF

0 голосов
/ 20 июля 2011

Я бы посоветовал вам использовать PHP Mailer для отправки писем с вашего PHP.Я использовал его с большим успехом на многих различных конфигурациях.В классе есть все необходимые методы для обработки кодировок, вложений, обычных заголовков, отправки через sendmail и т. Д. И т. Д.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...