php中的mail()问题

时间:2012-04-24 06:46:06

标签: php email

我正在使用以下代码,发送带有两个附件的邮件

我遇到的问题是,它只需要一个附件,我想通过邮件发送到附件,而且我没有得到自动回复,

任何人都可以帮助我,这是我的代码

<?php session_start();

$redirect_url = '../thanks.html';
$your_email ='name@domain.com';// <<=== update to your email address

$attachment_enabled = 1;
$autoresponder_enabled = 1;


    $name = $_POST['name'];
    $visitor_email = $_POST['email'];




function get_form_data(){

    global $REQUEST_METHOD;

    global $_POST;

    global $_GET;



    $vars = ($REQUEST_METHOD == 'GET') ? $_GET : $_POST;

    //strip spaces from all fields

    foreach ($vars as $k=>$v) $vars[$k] = trim($v);

    return $vars;

}


function _build_fields($vars){

    $skip_fields = array(

        'name', 

        'email', 

         'subject',

        'submitbtn');

    // order by numeric begin, if it exists

    $is_ordered = 0;

    foreach ($vars as $k=>$v) 

        if (in_array($k, $skip_fields)) unset($vars[$k]);



    $new_vars = array();

    foreach ($vars as $k=>$v){

        // remove _num, _reqnum, _req from end of field names

        $k = preg_replace('/_(req|num|reqnum)$/', '', $k);

        // check if the fields is ordered

        //if (preg_match('/^\d+[ \:_-]/', $k)) $is_ordered++;

        //remove number from begin of fields

        $k = preg_replace('/^\d+[ \:_-]/', '', $k);

        $new_vars[$k] = $v;

    }

    $vars = $new_vars;


    $max_length = 10; // max length of key field 

    foreach ($vars as $k=>$v) {

        $klen = strlen($k);

        if (($klen > $max_length) && ($klen < 40))

            $max_length = $klen;

    }



    if ($is_ordered)

        ksort($vars);



    // make output text

    $out = "";

    foreach ($vars as $k=>$v){

        $k = str_replace('_', ' ', $k);

        $k = ucfirst($k);

        $len_diff = $max_length - strlen($k);

        if ($len_diff > 0) 

            $fill = str_repeat('.', $len_diff);

        else 

            $fill = '';

        $out .= $k."$fill...: $v\n\n";

    }

    return $out;

}


$vars=get_form_data();
$out=_build_fields($vars);
$body = "A user  $name submitted the form:\n\n".$out;
//Auto Responser Function To Send Auto Respond



$autoresponder_from = $your_email;

$subject = "Page Edit Request";

$autoresponder_subject = "%subject% (autoresponse)";

$autoresponder_message = <<<MSG

Hi %name%,



Thank you for submitting the form.

--

MSG;


function auto_respond($vars){

    global $autoresponder_from, $autoresponder_message, $autoresponder_subject;

    /// replace all vars in message

    $msg = $autoresponder_message;

    preg_match_all('/%(.+?)%/', $msg, $out);

    $s_vars = $out[1]; //field list to substitute

    foreach ($s_vars as $k)

        $msg = str_replace("%$k%", $vars[$k], $msg);

    /// replace all vars in subject

    $subj = $autoresponder_subject;

    preg_match_all('/%(.+?)%/', $subj, $out);

    $s_vars = $out[1]; //field list to substitute

    foreach ($s_vars as $k)

        $subj = str_replace("%$k%", $vars[$k], $subj);

    //

    $_send_to = "$vars[name] <".$vars[email_from].">";

    $_send_from = $autoresponder_from;

   mail($_send_to, $subj, $msg, "From: $_send_from");

}

if(empty($errors))
{
        //send the email
        $to = $your_email;
        $subject="Page Edit Request";
        $from = $visitor_email;
        $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

        //Attach File if Attachment is done
        $files = array(); //files (field names) to attach in mail
        if (count($_FILES) && $attachment_enabled)
        {
            $files = array_keys($_FILES);
        }
        /*print_r($files);
        exit;*/
        if (count($files)){

        foreach ($files as $file){

            echo "hello";
            $file_name     = $_FILES[$file]['name'];

            $file_type     = $_FILES[$file]['type'];

            $file_tmp_name = $_FILES[$file]['tmp_name'];

            $file_cnt = "";

    if($file_name!='')
    {   
            $f=@fopen($file_tmp_name, "rb");

            if (!$f) 

                continue;

            while($f && !feof($f))

                $file_cnt .= fread($f, 4096);

            fclose($f);

            if (!strlen($file_type)) $file_type="applicaton/octet-stream";

            if ($file_type == 'application/x-msdownload')

                $file_type = "applicaton/octet-stream";






            $date_time = date('Y-m-d H:i:s');
            $mime_delimiter = md5(time());
            $mail = <<<EOF

This is a MIME-encapsulated message



--$mime_delimiter

$body

--------------------

REMOTE IP : $REMOTE_ADDR

DATE/TIME : $date_time

EOF;
            $data= chunk_split(base64_encode($file_cnt));
            $mail .= "\n--$mime_delimiter\n";

            $mail.="Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file_name\"\n"."Content-Disposition: attachment;\n" . " filename=\"$file_name\"\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
          //  $mail .= "Content-type: $file_type\n";

           // $mail .= "Content-Disposition: attachment; filename=\"$file_name\"\n";

           // $mail .= "Content-Transfer-Encoding: base64\n\n";

           // $mail .= chunk_split(base64_encode($file_cnt));

        }
        else
        {
            $mail=$body;
        }

    }

    $mail .= "\n--$mime_delimiter--";

    }
    else
    {
        $mail=$body;
    }
        $headers = "Mime-Version: 1.0\r\nFrom: $from \r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline";
        $headers .= "Reply-To: $visitor_email \r\n";
        mail($to,'Page Edit Request', $mail,$headers);

        if ($autoresponder_enabled) 

        auto_respond($vars);

        header("Location: $redirect_url");
}




// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?>

1 个答案:

答案 0 :(得分:2)

你的邮件构成非常丑陋而且非常错误。我能给你的最好的建议是停止重新发明轮子,只使用Swift邮件:http://swiftmailer.org/

我已经使用了他们的工具几次,它只是有效!

编辑不确定为什么会被投票,但fwiw这是Swift的代码:

$message = Swift_Message::newInstance()
    ->setSubject('Page Edit Request')
    ->setFrom(array($visitor_email))
    ->setTo(array($your_email))
    ->setBody($body);

if ($_FILES) {
    foreach (array_keys($_FILES) as $file) {
        if (UPLOAD_ERR_OK != $_FILES[$file]['error'] || !is_readable($_FILES[$file]['tmp_name'])) {
            continue;
        }
        $message->attach(Swift_Attachment::fromPath($_FILES[$file]['tmp_name']));
    }
}

$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);

$numSent = $mailer->send($message);