2012-12-28 86 views
4

我有一個應該將文件附加到外發電子郵件的功能。由於某些原因,它只發送空白文件。使用PHP將文件附加到電子郵件

有人可以幫忙嗎?我已經驗證過,這些文件本身正在正確上傳,並且處於該功能工作所需的確切位置。只有.PDF,.DOC和.DOCX允許

此外,這是一個在Windows Server ...(!我知道,我知道... YUCK)

下面是函數:

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) { 
    $file = str_replace('/','\\',$path.$filename); 
    $file_size = filesize($file); 
    $handle = fopen($file, "rb"); 
    $contenta = fread($handle, $file_size); 
    fclose($handle); 
    $content = chunk_split(base64_encode($contenta)); 
    $uid = md5(uniqid(time())); 
    $name = basename($file); 
    $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"; // use different content types here 
    $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."--"; 
    if (mail($mailto, $subject, "", $header)) { 
     return true; // or use booleans here 
    } else { 
     return false; 
    } 
} 

這裏是使用此代碼:

//resume 
$errors=""; 
$dbDir="/candidate-resources/files/temp/"; 
$baseDir=$_SERVER['DOCUMENT_ROOT'].$dbDir; 
$validTypes=array(".doc",".pdf",".docx"); 
$filesToAdd=array(); 
$atLeastOne=false; 
$valid=false; 
$qs=""; 
if(count($_FILES)>0){ 
    foreach($_FILES as $k=>$v){ 
     if($v['size']>0){ 
      $ext=substr($v['name'],strrpos($v['name'],".")); 
      if(!in_array($ext,$validTypes)){ 
       $errors='Only ".doc", ".docx", and ".pdf" files can be uploaded. "'.$ext.'" is not a valid file type.'; 
      } 
     } 
    } 
} 
$requireds=array("name","email","message"); 
foreach($_POST as $k=>$v){//check for injection and spammers 
    if(preg_match("/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i",$v) || strpos($v,"http://")!==false || strpos($v,"www.")!==false){ 
     $errors="HTML, website addresses, and scripting code are not allowed in any field. Please check your entries and try again."; 
    } 
    $post[$k]=strip_tags(trim(htmlentities($v))); 
} 
unset($_POST); 
foreach($requireds as $r){ 
    if(!strlen(trim($post[$r]))){ 
     $errors.="<li>".ucwords($r)."</li>"; 
    } 
} 
if(strlen(trim($errors))){ 
    $errors="These fields were left blank. Please fix and resubmit.<ul>".$errors."</ul>"; 
} 
else{ 
    if(ereg("([[:alnum:]\.\-]+)(\@[[:alnum:]\.\-]+\.+)",$post['email'])!=true){ 
     $errors="<p>You must enter a valid email address.</p>"; 
    } 
    else{ 
     $filename = ''; 
     $ext = ''; 
     // upload the file, then attach it to the email, then delete it 
     foreach($_FILES as $k=>$v){ 
      if($v['size']!=0){ 
       $atLeastOne=true; 
       $ext=substr($v['name'],strrpos($v['name'],"."));     
       move_uploaded_file($v['tmp_name'], $baseDir . "/" . $v['name']); 
       $filename = $v['name']; 
      } 
     } 
     $to = '[email protected]'; 
     $subject="Contact Form"; 
     $headers="From: ".$post["name"]." <".$post["email"].">\r\nReply-To: ".$post["email"]."\r\n"; 
     $message=$subject."\r\n=================================================\r\n\r\n"; 
     foreach($post as $k=>$v) { 
      if(strlen(trim($v))){ 
       $message.=ucwords(str_replace("_"," ",$k)).": {$v}\r\n"; 
      } 
     } 
     if(strlen($filename) > 0) { 
      mail_attachment($filename, $baseDir, $to, $post["email"], $post["name"], $post["email"], $subject, $message); 
      //now delete the temp file 
      if (file_exists(str_replace('/','\\',$baseDir.$filename))) { 
       unlink(str_replace('/','\\',$baseDir.$filename)); // delete it here only if it exists 
      } 
     }else{ 
      mail($to,$subject,$message,$headers); 
     } 
     $errors="true"; 
    } 
} 

請原諒......我只是繼承了這個代碼(即:#1 7歲,#2,現在他們想附加的能力文件到這封電子郵件)

回答

0

我改變了我的福nction周圍的一些,這一點也適用:

function mail_attachment($from, $fromname, $to, $subj, $text, $filename){ 
    $f   = fopen($filename,"rb"); 
    $un  = strtoupper(uniqid(time())); 
    $head  = "From: $fromname <$from>\n"; 
    $head  .= "To: $to\n"; 
    $head  .= "Subject: $subj\n"; 
    $head  .= "X-Mailer: PHPMail Tool\n"; 
    $head  .= "Reply-To: $from\n"; 
    $head  .= "Mime-Version: 1.0\n"; 
    $head  .= "Content-Type:multipart/mixed;"; 
    $head  .= "boundary=\"----------".$un."\"\n\n"; 
    $zag  = "------------".$un."\nContent-Type:text/html;\n"; 
    $zag  .= "Content-Transfer-Encoding: 8bit\n\n$text\n\n"; 
    $zag  .= "------------".$un."\n"; 
    $zag  .= "Content-Type: application/octet-stream;"; 
    $zag  .= "name=\"".basename($filename)."\"\n"; 
    $zag  .= "Content-Transfer-Encoding:base64\n"; 
    $zag  .= "Content-Disposition:attachment;"; 
    $zag  .= "filename=\"".basename($filename)."\"\n\n"; 
    $zag  .= chunk_split(base64_encode(fread($f, filesize($filename))))."\n"; 
    return @mail("$to", "$subj", $zag, $head); 
} 

(無需第三方包括)

7

開始使用Swiftmailerdocumentation)或PhpMailer,你的生活會更容易...

Swiftmailer例如:

require_once 'lib/swift_required.php'; 
$transport = Swift_MailTransport::newInstance(); 
$mailer = Swift_Mailer::newInstance($transport); 
$message = Swift_Message::newInstance('Wonderful Subject') 
    ->setFrom(array('[email protected]' => 'John Doe')) 
    ->setTo(array('[email protected]', '[email protected]' => 'A name')) 
    ->setBody('Here is the message itself') 
    ->attach(Swift_Attachment::fromPath('my-document.pdf')); 
$mailer->send($message); 

PHPMailer的例子:

$mail    = new PHPMailer(); // defaults to using php "mail()" 
$mail->SetFrom('[email protected]', 'First Last'); 
$mail->AddReplyTo("[email protected]","First Last"); 
$mail->AddAddress("[email protected]", "John Doe"); 
$mail->Subject = "PHPMailer Test Subject via mail(), basic"; 
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test 
$mail->MsgHTML($body); 
$mail->AddAttachment("images/phpmailer.gif");  // attachment 
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment 
if(!$mail->Send()) { 
    echo "Mailer Error: " . $mail->ErrorInfo; 
} else { 
    echo "Message sent!"; 
} 

我喜歡Swiftmailer,但你選擇你最好的選擇;-)

+0

我同意。但是,我確實很有用,但我沒有選擇包含任何第三方庫。抱歉。雖然給你一個加號 – Kevin

相關問題