我试图发送带有附件的php邮件,但总是返回false?

时间:2015-09-17 10:45:10

标签: php email

创建发送邮件的功能

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {

    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));

    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";

    // Messages for testing only, nobody will see them unless this script URL is visited manually
    if (mail($mailto, $subject, "", $header)) {
        return $header;
    } else {
        return false;
    }

}

要调用此函数,首先将文件保存到文件夹,然后将名称发送到函数

$test = mail_attachment($file_name, "resm/", $mailto, $from_mail, $from_name, $replyto, $subject, $message);

使用服务器godaddy共享主机,但是没有附件的简单邮件会返回真实并收到邮件,但是附件会返回false而不会收到任何邮件。

请帮忙。

1 个答案:

答案 0 :(得分:1)

我建议您尝试使用PHPMailer

  

许多PHP开发人员在其代码中使用电子邮件。唯一支持此功能的PHP函数是mail()函数。但是,它没有为使用基于HTML的电子邮件和附件等流行功能提供任何帮助。

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->From = 'from@example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}