8

我正在使用以下代码成功发送电子邮件。但现在我想用电子邮件附加一个文本文件(例如:test.txt)。任何的想法?

require_once "Mail.php";

$from = "Usman <from@example.com>";
$to = "Naveed <to@example.com>";
$subject = "subject";
$body = "";

$host = "smtp.gmail.com";
$username = "username";
$password = "password";

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

$smtp = Mail::factory( 'smtp', array('host' => $host,
          '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>" );
}
4

5 回答 5

11

发现此代码是google://pear mail attachment搜索的第一个命中。

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

$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = './files/example.zip';
$hdrs = array(
              'From'    => 'someone@domain.pl',
              'To'      => 'someone@domain.pl',
              'Subject' => 'Test mime message'
              );

$mime = new Mail_mime();

$mime->setTXTBody($text);
$mime->setHTMLBody($html);

$mime->addAttachment($file,'application/octet-stream');

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

$mail =& Mail::factory('mail', $params);
$mail->send('mail@domain.pl', $hdrs, $body); 
于 2010-07-21T13:19:51.117 回答
3

如果您另外使用 PHP PEAR Mail_Mime模块,它会提供适当的处理和编码以将附件合并为您的电子邮件的一部分。

于 2010-07-21T13:19:33.300 回答
2

这是您要查找的代码:

<?php
require_once "Mail.php"; // PEAR Mail package
require_once ('Mail/mime.php'); // PEAR Mail_Mime packge

$from = "Robert Davis <robertdavis@pobox.com>";
$to = "Sam Hill <sam.hill@aol.com>";
$subject = 'Test mime message with an attachment';

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

$text = 'Text version of email';// text and html versions of email.
$html = '<html><body>HTML version of email. <strong>This should be bold</strong></body>        </html>';

$file = './sample.txt'; // attachment
$crlf = "\n";

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

//do not ever try to call these lines in reverse order
$body = $mime->get();
$headers = $mime->headers($headers);

$host = "sasl.smtp.pobox.com";
$username = "robertdavis@pobox.com";
$password = "Kdu48Adi3";

$smtp = Mail::factory('smtp', array ('host' => $host, '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>");
}
?>
于 2013-02-04T14:11:38.090 回答
1

使用 PHP 发送电子邮件总是感觉有点像在挣扎。如果您能够使用它们,我会推荐这两个用于 PHP 的邮件库之一:

于 2010-07-21T13:30:43.283 回答
0

您似乎正在使用 PEAR Mail 包。

看看 Mail_Mine 对象,它可以完成您正在尝试做的事情,并且有一种添加附件的简单方法(只需调用 addAttachments)。

http://pear.php.net/manual/en/package.mail.mail-mime.php

于 2010-07-21T13:20:30.803 回答