如何使用带附件的PEAR Mail包发送带有PHP的电子邮件

Ric*_*ata 4 php email pear mail-mime

我正在尝试使用带附件的PEAR邮件包发送带有PHP的电子邮件.电子邮件成功发送了我从互联网上获得的代码.但是,附件不会被发送或附加.我哪里出错了,下面是我的代码.

<?php

require_once "Mail.php"; 
require_once "Mail/mime.php";

$from = "<my.name@company.com>";
$to = "<myname@gmail.com>";
$subject = "Testing email from PHP with attachment";
$body = "Testing email from PHP with attachment";
$file = "invoices/PRINV7_3.pdf";
$host = "host";
$port = "25";
$username = "username";
$password = "password";

$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);

$mime = new Mail_mime();

if ($mime->addAttachment($file,'application/pdf')){
    echo "attached successfully! </br>";
} else {
    echo "Nope, failed to attache!! </br>";
}

$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'port' => $port,
    'auth' => true,
    'username' => $username,
    'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
  echo("<p>" . $mail->getMessage() . "</p>");
 } else {
  echo("<p>Message successfully sent!</p>");
 }

?>
Run Code Online (Sandbox Code Playgroud)

ARI*_*ANA 7

我没有检查这段代码所以如果不工作我很抱歉

include 'Mail.php';
include 'Mail/mime.php';

$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = '/home/richard/example.php';
$crlf = "\n";
$hdrs = array(
    'From' => 'you@yourdomain.com',
    'Subject' => 'Test mime message'
);
$host = "host";
$port = "25";
$username = "username";
$password = "password";

$mime = new Mail_mime(array('eol' => $crlf));

$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain');

$body = $mime->get();
$hdrs = $mime->headers($hdrs);

$mail = & Mail::factory('smtp',
  array ('host' => $host,
    'port' => $port,
    'auth' => true,
    'username' => $username,
    'password' => $password));
$mail->send('postmaster@localhost', $hdrs, $body);
Run Code Online (Sandbox Code Playgroud)


ame*_*ren 2

我相信您需要将$mime对象中的标头添加到您的$headers

$attachmentheaders = $mime->headers($headers);
Run Code Online (Sandbox Code Playgroud)

然后更改您的邮件呼叫:

$mail = $smtp->send($to, $attachmentheaders, $body);
Run Code Online (Sandbox Code Playgroud)

这是一个可能有帮助的教程: http://www.html-form-guide.com/email-form/php-email-form-attachment.html