php mail()函数附件和body都是空的

时间:2016-03-19 10:30:50

标签: php email

我一直难以尝试调试我的php mail()代码。我已经在下面包含了整个PHP块,所以请原谅不相关的格式和部分(rCaptcha,字段验证等)。

我遇到的问题是,当电子邮件通过时... 1)没有电子邮件正文...和2)附件是空的。

如果我注释掉这行“$ body。= $ my_attachment;”我收到了正文中的预期文本,并且毫无疑问没有附件。

任何人都可以发现我无疑的新秀错误吗?我期待一些回复建议我使用PHP邮件库,我现在正在调查,但是对于我的理解和教育,我会感谢一些针对我的错误的具体反馈。

感谢您的帮助。

<?php
/********************************************
/ Start processing the email
/*******************************************/   
# We'll make a list of error messages in an array
$messages = array();
$upload_folder = "uploads/";
// a random hash will be necessary to send mixed content
$separator = md5(time());

// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;

// Change this to YOUR address
$recipient = XXX@XXX>COM;
$email = $_POST['myemail'];
$phone = $_POST['phone'];
$realName = $_POST['name'];
$subject = "WEB CONTACT: Careers" ;

$body = "--" . $separator . $eol;
$body .= "FROM: " . $realName . 
        "\r\nPHONE: " . $phone .
        "\r\nEMAIL: " . $email .
        "\r\nCONTACT ME VIA: " . $_POST['contact_me'] .
        "\r\nMESSAGE:" . $_POST['mymessage'] ;

/********************************************
/ ATTACHMENT
/*******************************************/
//Get the uploaded file information
$name_of_uploaded_file =
    basename($_FILES['uploaded_file']['name']);

//get the file extension of the file
$type_of_uploaded_file =
    substr($name_of_uploaded_file,
    strrpos($name_of_uploaded_file, '.') + 1);

$size_of_uploaded_file =
    $_FILES["uploaded_file"]["size"]/1024;//size in KBs

//Settings
$max_allowed_file_size = 1024; // size in KB
$allowed_extensions = array("pdf", "doc", "txt");

//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
  $messages[] = "Size of file should be less than " . $max_allowed_file_size;
}

//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
  if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
  {
    $allowed_ext = true;
  }
}

if(!$allowed_ext)
{
  $messages[] = "The uploaded file is not supported file type. ".
  " Only the following file types are supported: ".implode(',',$allowed_extensions);
}   

//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];

if(is_uploaded_file($tmp_path))
{
  if(!copy($tmp_path,$path_of_uploaded_file))
  {
    $messages[] = 'Error while copying the uploaded file';
  }
}

// attachment

    $file = $upload_folder . "/" . $name_of_uploaded_file;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));



/***********************************************************
// reCAPTCHA your recaptcha secret key
***********************************************************/
$secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

if(isset($_POST['email']))
{
    $email=$_POST['email'];
}
if(isset($_POST['comment']))
{
    $email=$_POST['comment'];
}
if(isset($_POST['g-recaptcha-response']))
{
    $captcha=$_POST['g-recaptcha-response'];
}
        $ip = $_SERVER['REMOTE_ADDR'];
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
        $responseKeys = json_decode($response,true);
        if(intval($responseKeys["success"]) !== 1) {
          $messages[] = "The reCaptcha Question was not answered correctly. I am begining to suspect that you are a robot.";
        } 
/***********************************************************
// END reCAPTCHA 
***********************************************************/        

/***********************************************************
// Message format validations
***********************************************************/
# Allow only reasonable email addresses
if (!preg_match("/^[\w\+\-.~]+\@[\-\w\.\!]+$/", $email)) {
$messages[] = "That is not a valid email address.";
}
# Allow only reasonable real phone numbers
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$messages[] = "The phone number must only include numbers, spaces, brackets(), and '+'.";
}
# Allow only reasonable real names
if (!preg_match("/^[\w\ \+\-\'\"]+$/", $realName)) {
$messages[] = "The real name field must contain only " .
"alphabetical characters, numbers, spaces, and " .
"reasonable punctuation. We apologize for any inconvenience.";
}
# CAREFUL: don't allow hackers to sneak line breaks and additional
# headers into the message and trick us into spamming for them!
$subject = preg_replace('/\s+/', ' ', $subject);
# Make sure the subject isn't blank afterwards!
if (preg_match('/^\s*$/', $subject)) {
$messages[] = "Please choose area and office for your message.";
}

# Make sure the message has a body
if (preg_match('/^\s*$/', $body)) {
$messages[] = "Your message was blank. Did you mean to say " .
"something?"; 
}
  if (count($messages)) {
    # There were problems, so tell the user and
    # don't send the message yet
    foreach ($messages as $message) {
      echo("<p>$message</p>\n");
    }
    echo("<p>Click the back button and correct the problems. " .
      "Then click Send Your Message again.</p>");
  } 
  //else 
  {
    # Send the email - we're done


    // main header (multipart mandatory)
    $headers = "From: " . $realName . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;

    // message
    $headers .= "--" . $separator . $eol;
    $headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 8bit" . $eol;
    $headers .= $body . $eol;

    // attachment
    $my_attachment ="";
    $my_attachment .= "--" . $separator . $eol;
    $my_attachment .= "Content-Type: application/octet-stream; name=\"" . $name_of_uploaded_file . "\"" . $eol;
    $my_attachment .= "Content-Disposition: attachment; filename=\"" . $name_of_uploaded_file . "\"" . $eol;
    $my_attachment .= "Content-Transfer-Encoding: base64" . $eol;
    $my_attachment .= "Content-Disposition: attachment" . $eol;
    $my_attachment .= $content . $eol;
    $my_attachment .= "--" . $separator . "--";


    $body .=  $my_attachment ;



mail($recipient,
      $subject,
      $body,
      $headers
     ); 
    echo("<p>Your message has been sent. Thank you!</p>\n");
  }
?>

1 个答案:

答案 0 :(得分:0)

您可以使用PHPmailer类发送邮件。发送邮件非常简单。

使用PHPMailer:

  • 从此处下载PHPMailer脚本:http://github.com/PHPMailer/PHPMailer
  • 提取存档并将脚本文件夹复制到项目中方便的位置。
  • 包含主脚本文件 - require_once('path/to/file/class.phpmailer.php');

现在,发送附带电子邮件的过程非常困难,非常简单:

$email = new PHPMailer();
$email->From      = 'you@example.com';

$email->FromName  = 'Your Name';

$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

只有一行$ email-&gt; AddAttachment();添加附件。