2011-10-11 4 views
-1

나는 내 질문과 유사한 질문이 많다는 것을 알고 있으며, 그 중 일부를 통해 살펴본 결과 아무도 내 질문에 대답하지 않은 것으로 나타났습니다.이메일 SQL 첨부 문제

기본적으로 자신의 데이터베이스 덤프를 생성하여 전자 메일로 보내는 클라이언트 용 스크립트를 만들었습니다. 아래 코드를 게시하면 데이터베이스 정보가 스크립트를 통해 생성되고 물리적 SQL 파일이 생성되지 않습니다. 서버에서 대신 변수에 모두 추가 한 다음 변수를 사용하여 데이터베이스 정보를 전자 메일 헤더에 첨부합니다.

또한 전자 메일 첨부 파일 코드를 사용하여 정상적으로 작동하지만 실제로는 파일이 실제로 존재하므로 문제라고 생각하기 시작했습니다.

<?php 

    //Script configuration section. 
    $D_hostname = 'localhost'; # Database hostname. 
    $D_username = 'username'; # Database username. 
    $D_password = 'password'; # Database password. 
    $D_database = 'database'; # Database name. 

    $E_from = '{BLOG BACKUP} <[email protected]>'; # From header. 
    $E_subject = '[' . date('d-m-Y') . ']: This weeks database backup.'; # Email subject. 
    $E_content = 'This weeks database backup has been created, please find it attached to this email. Remember to save a copy and retain this email too!<br />'; #Email content. 
    $E_filename = date('d-m-Y') . '_blog_backup.sql'; #Attachment filename. 
    $E_filetype = 'application/octet-stream'; # Attachment type. 
    $E_recipients = '[email protected], [email protected]'; #Email recipients. 

    //Connect to the database. 
    $connection = mysql_connect($D_hostname, $D_username, $D_password); 

    //Select the database 
    mysql_select_db($D_database, $connection); 

    //Set up an empty array. 
    $tables = array(); 

    //Get a list of all the databases tables. 
    $Q_show_tables = mysql_query('SHOW TABLES'); 

    //Add each table to the array. 
    while($R_show_tables = mysql_fetch_row($Q_show_tables)){ 
     $tables[] = $R_show_tables[0]; 
    } 

    //Get all rows for each table and create a mySQL query. 
    foreach($tables as $table) { 

     //Get all rows from the table. 
     $Q_get_rows = mysql_query('SELECT * FROM '.$table); 
     $C_get_rows = mysql_num_fields($Q_get_rows); 

     //Add a drop clause for the table 
     $data_row .= 'DROP TABLE ' . $table . ';'; 

     //Get create table info. 
     $Q_create_table = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table)); 

     //Add the create table clause to the query. 
     $data_row.= "\n\n" . $Q_create_table[1] . ";\n\n"; 

     //Now gather all of the rows. 
     for ($int_01 = 0; $int_01 < $C_get_rows; $int_01++) { 
      while($R_get_rows = mysql_fetch_row($Q_get_rows)) { 

       //Add the insert clause. 
       $data_row .= 'INSERT INTO ' . $table . ' VALUES ('; 

       //For each field write out a row. 
       for($int_02 = 0; $int_02 < $C_get_rows; $int_02++) { 
        $R_get_rows[$int_02] = addslashes($R_get_rows[$int_02]); 
        $R_get_rows[$int_02] = ereg_replace("\n","\\n",$R_get_rows[$int_02]); 
        if (isset($R_get_rows[$int_02])) { 
         $data_row .= '"'.$R_get_rows[$int_02].'"' ; 
        } else { 
         $data_row .= '""'; 
        } 
        if ($int_02 < ($num_fields-1)) { 
         $data_row .= ','; 
        } 
       } 
      $data_row .= ");\n"; 
      } 
     } 
     $data_row .="\n\n\n"; 
    } 

    //Split and encode the data. 
    $data_split = chunk_split(base64_encode($data_row)); 

    //Create a unique boundary 
    $new_boundary = md5(time()); 

    //This is your basic header information such as who the email is from and the date it was sent. 
    $mail_header .= 'From: ' . $E_from . "\r\n"; 
    $mail_header .= 'Date: ' . date('r') . "\r\n"; 

    //This part of the header first defines to the email client that it is a multipart message and adds the emails content/body. 
    $mail_header .= 'Content-Type: multipart/mixed; boundary="' . $new_boundary . '"' . "\r\n\r\n"; 
    $mail_header .= 'MIME-Version: 1.0' . "\r\n"; 
    $mail_header .= 'This is a multi-part message in MIME format' . "\r\n"; 
    $mail_header .= '--' . $new_boundary . "\r\n"; 
    $mail_header .= 'Content-Type:text/html; charset="iso-8859-1"' . "\r\n"; 
    $mail_header .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n"; 
    $mail_header .= $E_content . "\r\n\r\n"; 

    //This part of the header is for the attachment and includes the contents of the file, the files name and other information. 
    $mail_header .= '--' . $new_boundary . "\r\n"; 
    $mail_header .= 'Content-Type: ' . $E_filetype . '; name="' . $E_filename . '"' . "\r\n"; 
    $mail_header .= 'Content-Transfer-Encoding: base64' . "\r\n"; 
    $mail_header .= 'Content-Disposition: attachment; filename="' . $E_filename . '"' . "\r\n\r\n"; 
    $mail_header .= $data_split . "\r\n\r\n"; 

    //This is needed to stop any rendering errors by email clients and signifies the end of the emails header. 
    $mail_header .= '--' . $new_boundary . '--' . "\r\n"; 

    //This mails out all of the above. 
    mail($E_recipients, $E_subject, '', $mail_header); 

?> 

문제

: 이메일이 무리 메일 클라이언트 나 핫메일에 전혀 표시되지 않는 첨부 파일 및 메시지 내용을 전송, 아직 Gmail에서 잘 작동. 메일 헤더에 문제가있는 것 같지만 오류는 볼 수 없습니다.

이메일 헤더에 문제가있는 사람은 누구입니까? 그렇다면 문제를 해결하는 방법에 대해 조언 해 줄 수 있습니까?

항상 도움을 주시면 대단히 감사하겠습니다.

+0

나는 Gmail에서 정상적으로 표시되지만 Hotmail이나 Horde에서는 표시되지 않음을 유의해야합니다.다른 메일 클라이언트를 시도하지 않았습니다. – RobFos

+0

사이드 노트로, 전자 메일은 가장 안전한 커뮤니케이션 수단이 아닙니다. DB를 보내면 위험합니다. –

+0

해결책은 아니지만 코드를 살펴볼 때 [ ezMail] (http://ezcomponents.org/docs/tutorials/Mail)에서 PHP를 통해 메일을 쉽고 빠르게 보내는 모든 문제를 처리 할 수 ​​있습니다. 바퀴를 재발 명할 필요가 없습니다. –

답변

1

성령의 몰리!

mime 개체를 사용하여 올바른 형식의 전자 메일 메시지를 만드는 것은 간단한 작업이 아닙니다. 난 metamail 코드를 해킹했지만 그것을 처리하기 위해 내 자신의 PHP 코드를 작성하지 않을 것이다. 필자가 PHP (metamail, mutt)에서 호출 할 수있는 mime 가능 메일 클라이언트의 기본 구현이없는 곳에서 자유롭게 사용할 수있는 libs 중 하나를 사용하여 (phpmailer, swiftmailer가 확실한 후보자 임) 사용하고 싶습니다.

필자가 피하는 경향이있는 또 다른 사항은 PHP 스크립트의 메모리에 데이터베이스 백업 표현을 만드는 것입니다. 내가하지 않을

몇 가지 다른 사항은 다음과 같습니다

  • 인과 관계의 자연과 조작 DB 입력을
  • 을 탈출 addslashes를 사용하여
  • 피할
  • 을 구분 할 우려가있는 모듈 프로그래밍을 사용하여 이메일을 통해
  • transfering 가능성이 매우 큰 파일 (대부분의 MTA는 이메일의 크기를 제한합니다)

다시 시작하는 것이 좋습니다 - cron 작업을 설정하여 백업을 로컬 파일로 추출한 다음 파일에 액세스 할 수 있도록 PHP를 작성하고 사용자에게 백업을 다운로드 할 수있는 링크를 전자 메일로 보냅니다.

+0

네가 그 일을 처리하는 가장 좋은 방법이라고 생각합니다. of는 데이터베이스가 클라이언트에게 전자 메일로 전송 될 것이라는 생각이 마음에 들었고 내 서버의 데이터베이스 리포지토리로 이동하지 않고 무언가가 잘못되어 백업이 없다고 불평하는 것에 대해 걱정할 필요가 없었습니다. 비록 그것이 내 잘못이 아니지만 나는 대립과 불일치없이 오히려 할 것입니다. 그러나 나는 데이터베이스를 이메일로 보내지 않고도이 모든 것을 처리 할 새로운 스크립트를 작성할 것이다. 답변 해주셔서 감사합니다! – RobFos

0

신체를 시체에 넣어야합니다. MIME 메시지 일 수 있으므로 머리글을 포함 할 수 있습니다. 그러나 기술적으로 메시지 본문이며 이동해야하는 곳입니다.

또한 \r\n 시퀀스가 ​​필요합니다.이 은 (는)이 잘못되었지만 포함시키지 않아야합니다. 메시지를 작성/보내려면 아래 코드를 시도하십시오.

//Split and encode the data. 
$data_split = chunk_split(base64_encode($data_row)); 

//Create a unique boundary 
$new_boundary = '-------'.md5(time()).'-----'; 

//This is your basic header information such as who the email is from and the date it was sent. 
$mail_header = 'From: ' . $E_from . "\r\n"; 
$mail_header .= 'Date: ' . date('r') . "\r\n"; 

//This part of the header first defines to the email client that it is a multipart message and adds the emails content/body. 
$mail_header .= 'Content-Type: multipart/mixed; boundary="' . $new_boundary . '"' . "\r\n"; 
$mail_header .= 'MIME-Version: 1.0' . "\r\n"; 

// The body (multipart message) starts here: 
$mail_body = 'This is a multi-part message in MIME format' . "\r\n"; 

// HTML content of the email 
$mail_body .= "$new_boundary\r\n"; 
$mail_body .= 'Content-Type: text/html; charset="iso-8859-1"' . "\r\n"; 
$mail_body .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n"; 
$mail_body .= $E_content . "\r\n"; 

// This part of the body is for the attachment and includes the contents of the file, the files name and other information. 
$mail_body .= "$new_boundary\r\n"; 
$mail_body .= 'Content-Type: ' . $E_filetype . '; name="' . $E_filename . '"' . "\r\n"; 
$mail_body .= 'Content-Transfer-Encoding: base64' . "\r\n"; 
$mail_body .= 'Content-Disposition: attachment; filename="' . $E_filename . '"' . "\r\n\r\n"; 
$mail_body .= $data_split . "\r\n"; 

//This is needed to stop any rendering errors by email clients and signifies the end of the email's body. 
$mail_body .= "$new_boundary--"; 

//This mails out all of the above. 
mail($E_recipients, $E_subject, $mail_body, $mail_header); 
+0

그는 몸에 추가하고 있습니다. 예, 그는이 코드가 무엇을하는지 모릅니다. 그러나이 코드는 시체를 시체에 추가하는 것입니다. –

+0

@ Col.Shrapnel 사실이 아닙니다. 코드가 빈 문자열을 본문에 전달하고 전체 메시지를 헤더에 전달합니다. – DaveRandom

+0

@DaveRandom 안녕 Dave, 답장을 보내 주셔서 대단히 감사합니다. 불행히도 작동하지 않습니다. 헤더에 전달해야한다는 점이 긍정적입니다. 첨부 파일을 이메일로 보내기 전에 동일한 코드를 사용했습니다. 유일한 차이점은 다른 스크립트에서 파일이 서버에 실제로 존재한다는 것은 여기에 파일이 생성되지 않았기 때문에 정보가 변수의 헤더에 추가 된 것이고 이것이 문제라고 생각합니다. 그러나 나는 당신의 코드를 시험해 보았습니다. 기본적으로 이메일 내용으로 헤더를 썼습니다. 그리고 좋은 1-2 분 동안 브라우저를 동결 시켰습니다. D : – RobFos

관련 문제