PHP:如何使用smtp设置发送带附件的电子邮件?

时间:2010-07-21 13:13:41

标签: php smtp email email-attachments

我正在使用以下代码成功发送电子邮件。但现在我想附上一个带有电子邮件的文本文件(例如: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>" );
}

5 个答案:

答案 0 :(得分: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); 

答案 1 :(得分:3)

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

答案 2 :(得分: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>");
}
?>

答案 3 :(得分:1)

使用PHP发送电子邮件总觉得有点像斗争。如果你能够使用它们,我会推荐这两个邮件库中的一个用于PHP:

答案 4 :(得分:0)

您似乎正在使用PEAR Mail包。

查看Mail_Mine对象,该对象可以执行您要执行的操作,并且可以轻松添加附件(只需调用addAttachments)。

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