【问题标题】:send email with attachment using php使用 php 发送带附件的电子邮件
【发布时间】:2012-01-15 21:49:36
【问题描述】:

我使用此代码使用 php 发送带有附件的电子邮件,但附件中有一些错误,因为我收到一封电子邮件并且附件出现在内容中。在我使用相同的代码并且它成功运行之前。为什么???

<?php
// sending email with attachments

    function sendEmail($to,$from,$file,$ext){

      $to = "admin@fuwant.com";
     $from = "noor@fuwant.com";
      $subject = "Translation Request";

  $random_hash = md5(date('r', time()));

  $headers = "From: sahar@fuwant.com\r\nReply-To: admin@fuwant.com";

  $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

  $attachment = chunk_split(base64_encode(file_get_contents("Test.doc")));

  $output = "
        --PHP-mixed-$random_hash;
        Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
        --PHP-alt-$random_hash
        Content-Type: text/plain; charset='iso-8859-1'
        Content-Transfer-Encoding: 7bit

        Hello World!
        This is the simple text version of the email message.

        --PHP-alt-$random_hash
        Content-Type: text/html; charset='iso-8859-1'
        Content-Transfer-Encoding: 7bit

        <h2>Hello World!</h2>
        <p>This is the <b>HTML</b> version of the email message.</p>

        --PHP-alt-$random_hash--

        --PHP-mixed-$random_hash
        Content-Type: application/doc; name=Test.doc
        Content-Transfer-Encoding: base64
        Content-Disposition: attachment

        $attachment
        --PHP-mixed-$random_hash--";
      $send =  @mail($to, $subject, $output, $headers);
  return $send;
  }
?>

请帮忙。

【问题讨论】:

标签: php email attachment


【解决方案1】:

为什么不使用phpmailer?附件示例:

function mandaMail ($nombredest, $maildest, $asunto, $cuerpo) {
require_once("mailer/class.phpmailer.php");
$mail = new PHPMailer(true);
$mail->IsSMTP();

try {
    $mail->Host = "xxxx"; $mail->Port = 25; // smtp server
    $mail->SMTPAuth = true;
    $mail->Username = "xxxx"; // smtp username
    $mail->Password = "xxxx"; // smtp pass
    $mail->AddReplyTo("xxxx", "xxxx"); // email & name
    $mail->SetFrom("xxxx", "xxxx"); // similar to up value

    $mail->AddAddress($maildest, $nombredest);
    $mail->Subject = $asunto;
    $mail->MsgHTML(file_get_contents($cuerpo));

    $mail->AddAttachment("xxxx", "xxxx"); // attachments directory, attachment name (ie: dir/blah.jpg, blah.jpg)
    $mail->Send();

} catch (phpmailerException $e) { echo $e->errorMessage();
} catch (Exception $e) { echo $e->getMessage(); }

【讨论】:

    【解决方案2】:

    您可以按照this 教程描述的方式进行操作,也可以使用PEAR 模块之一按照this 教程描述的方式发送带有附件的电子邮件。

    使用 PEAR 可能是更好的选择,因为它更容易操作。唯一需要注意的是 PEAR 并非在所有主机上都可用。

    【讨论】:

      【解决方案3】:

      我正在使用这个:

      function attachfile($file, $type = "application/octetstream")  {
          if(!($fd = fopen($file, "r"))) {
            $this->errstr = "Error opening $file for reading.";
            return 0;
          }
          $_buf = fread($fd, filesize($file));
          fclose($fd);
      
          $fname = $file;
          for($x = strlen($file); $x > 0; $x--)
            if($file[$x] == "/")
              $fname = substr($file, $x, strlen($file) - $x);
      
          // Convert to base64 becuase mail attachments are not binary safe.
          $_buf = chunk_split(base64_encode($_buf));
      
          $this->attachments[$file] = "\n--" . $this->boundary . "\n";
          $this->attachments[$file] .= "Content-Type: $type; name=\"$fname\"\n";
          $this->attachments[$file] .= "Content-Transfer-Encoding: base64\n";
          $this->attachments[$file] .= "Content-Disposition: attachment; " .
                                           "filename=\"$fname\"\n\n";
          $this->attachments[$file] .= $_buf;
      
          return 1;
        }
      

      【讨论】:

        【解决方案4】:

        您的代码将无法正常工作,因为电子邮件不支持空格

          $output = "
               --PHP-mixed-$random_hash;
               Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
               --PHP-alt-$random_hash
               Content-Type: text/plain; charset='iso-8859-1'
               Content-Transfer-Encoding: 7bit
        

        你必须使用没有空格

         $output = "
         --PHP-mixed-$random_hash;
         Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
         --PHP-alt-$random_hash
         Content-Type: text/plain; charset='iso-8859-1'
         Content-Transfer-Encoding: 7bit
        

        【讨论】:

          【解决方案5】:

          我正在使用这个和(没有使用 PHPMailer ),希望这对你有帮助。

          <form enctype="multipart/form-data" method="POST" action="">
              <label>Your Name <input type="text" name="sender_name" /> </label> <br>
              <label>Your Email <input type="email" name="sender_email" /> </label> <br>
              <label>Subject <input type="text" name="subject" /> </label> <br>
              <label>Message <textarea name="message"></textarea> </label> <br>
              <label>Attachment <input type="file" name="my_file" /></label><br>
              <label><input type="submit" name="button" value="Submit" /></label>
          </form>
          
          <?php 
          echo "<pre>";print_r($_REQUEST);echo "</pre>"; //comment this line
          echo "<pre>";print_r($_FILES);echo "</pre>"; //comment this line
          if($_POST && isset($_FILES['my_file']))
          {
          
              $from_email         = 'noreply@your_domain.com'; //from mail, it is mandatory with some hosts
              $recipient_email    = 'your-emailid@gmail.com'; //recipient email (most cases it is your personal email)
          
              //Capture POST data from HTML form and Sanitize them, 
              $sender_name    = filter_var($_POST["sender_name"], FILTER_SANITIZE_STRING); //sender name
              $reply_to_email = filter_var($_POST["sender_email"], FILTER_SANITIZE_STRING); //sender email used in "reply-to" header
              $subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING); //get subject from HTML form
              //$message        = filter_var($_POST["message"], FILTER_SANITIZE_STRING); //message
              $message        = "Name : ".$sender_name."\nMessage : ".$_POST["message"]; //message
          
              //Get uploaded file data
              $file_tmp_name    = $_FILES['my_file']['tmp_name'];
              $file_name        = $_FILES['my_file']['name'];
              $file_size        = $_FILES['my_file']['size'];
              $file_type        = $_FILES['my_file']['type'];
              $file_error       = $_FILES['my_file']['error'];
          
              if($file_error > 0)
              {
                  die('Upload error or No files uploaded');
              }
              //read from the uploaded file & base64_encode content for the mail
              $handle = fopen($file_tmp_name, "r");
              $content = fread($handle, $file_size);
              fclose($handle);
              $encoded_content = chunk_split(base64_encode($content));
          
                  $boundary = md5("sanwebe");
                  //headers
                  $headers = "MIME-Version: 1.0\r\n"; 
                  $headers .= "From:".$from_email."\r\n"; 
                  $headers .= "Reply-To: ".$reply_to_email."" . "\r\n";
                  $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 
          
                  //body plain text 
                  $body = "--$boundary\r\n";
                  $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
                  $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
                  $body .= chunk_split(base64_encode($message)); 
          
                  //attachment file
                  $body .= "--$boundary\r\n";
                  $body .="Content-Type: $file_type; name=".$file_name."\r\n";
                  $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
                  $body .="Content-Transfer-Encoding: base64\r\n";
                  $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
                  $body .= $encoded_content; 
              $sentMail = @mail($recipient_email, $subject, $body, $headers);
              if($sentMail) //output success or failure messages
              {       
                  die('Thank you for your email');
              }else{
                  die('Could not send mail!');  
              }
          }
          ?>
          

          【讨论】:

            【解决方案6】:

            这种方式也很有效:

            $to = 'bla@test.de'; 
             $from = 'blub@test.de'; 
            $fromName = 'Me'; 
            
            
            $subject = 'Hello';  
            
            
            $file = "D:/xxxxxxx/kanal_uebersicht.pdf"; 
            
            
            $htmlContent= "Sehr geehrte Damen und Herren, \r\n";
             $htmlContent.= "blabla. \r\n";
            $htmlContent.= "Mit freundlichen Grüßen, \r\n";
            $htmlContent.= "blabla. \r\n";
            
            
            
            $headers = "From: $fromName"." <".$from.">"; 
            
            
            $semi_rand = md5(time());  
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  
            
            $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 
            
            
            $message .= "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"UTF-8\"\n" . 
            "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";  
            
            
            if(!empty($file) > 0){ 
                if(is_file($file)){ 
                    $message .= "--{$mime_boundary}\n"; 
                    $fp =    @fopen($file,"rb"); 
                    $data =  @fread($fp,filesize($file)); 
            
                    @fclose($fp); 
                    $data = chunk_split(base64_encode($data)); 
                    $message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .  
                    "Content-Description: ".basename($file)."\n" . 
                    "Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" .  
                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
                } 
            } 
            $message .= "--{$mime_boundary}--"; 
            $returnpath = "-f" . $from; 
            
            
            $mail = @mail($to, $subject, $message, $headers, $returnpath); 
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-08-02
              • 2011-01-02
              • 2012-06-15
              • 2020-11-20
              • 2014-02-28
              • 2013-08-26
              相关资源
              最近更新 更多