【发布时间】:2014-04-12 20:14:42
【问题描述】:
我正在尝试使用以下代码从 PHP 脚本通过电子邮件将文本文件作为附件发送:http://webcheatsheet.com/php/send_email_text_html_attachment.php#attachment
<?
$subject = 'Requested File';
$random_hash = md5(date('r', time()));
$headers = "From: email@email.com\r\nReply-To: email@email.com";
$headers .= "\r\nContent-Type: myltipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents('path/test.txt')));
ob_start();
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="test.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
我不是 PHP 开发人员,使用它的经验非常有限,执行此脚本时我没有收到任何错误,但我也没有收到电子邮件...任何想法为什么?或者我应该具体看什么?
感谢您的任何提示!
编辑: 根据 cmets,我尝试使用 SwiftMailer,但无法使用以下代码使其工作: $message = Swift_Message::newInstance();
// Give the message a subject
$message->setSubject('Your subject');
// Set the From address with an associative array
$message->setFrom(array('email@email.com' => 'From Name'));
// Set the To addresses with an associative array
$message->setTo(array('email@email.com', 'email@email.com' => 'Name'));
// Give it a body
$message->setBody('Here is the message itself');
// And optionally an alternative body
$message->addPart('<q>Here is the message itself</q>', 'text/html');
// Optionally add any attachments
$message->attach(Swift_Attachment::fromPath('path/test.csv'));
同样,这段代码执行没有任何错误,但没有发送电子邮件……我错过了什么?
【问题讨论】:
-
第一步:Enable error reporting。第 2 步:从代码中删除那些讨厌的
@运算符。它们会抑制有用的错误消息,让您的生活更加艰难。 -
使用 phpmailer 类,检查这个线程:stackoverflow.com/questions/15064619/…希望它有帮助!
-
停止手工构建论文,使用邮件库
-
这里已经回答了这个问题:stackoverflow.com/questions/12301358/… 但是我鼓励使用 Swiftmailer 而不是 PHPMailer,说明在他们的手册中:swiftmailer.org/docs/messages.html#attaching-files
-
尝试删除
@mail中的 @ 符号 --- 在某些情况下,删除它会产生重大影响。另一件事是您的$to没有收件人,这很可能是问题所在。