3

これが私の試みです。私が間違っていることを教えてもらえますか?

allputcsv は、配列を csv 形式の文字列に変換します。これは base64 でエンコードされ、チャンクが分割されます。これは通常のファイルでも機能するようですが、文字列を使用しているため、何か別のことを行う必要がありますか?

<?php

function sputcsv($row, $delimiter = ',', $enclosure = '"', $eol = "\n")
{
    static $fp = false;
    if ($fp === false)
    {
        $fp = fopen('php://temp', 'r+');
    }
    else
    {
        rewind($fp);
    }

    if (fputcsv($fp, $row, $delimiter, $enclosure) === false)
    {
        return false;
    }

    rewind($fp);
    $csv = fgets($fp);

    if ($eol != PHP_EOL)
    {
        $csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
    }
    return $csv;
}

function allputcsv($arr) {
    $str = "";
    foreach($arr as $val) {
        $str .= sputcsv($val);
    }
    return $str;
}

function send_mail($arr) {
    $to = 'youraddress@example.com'; 
    $subject = 'Test email with attachment'; 
    $random_hash = md5(date('r', time())); 
    $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; 
    $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"--".$random_hash."\""; 
    $attachment = chunk_split(base64_encode(allputcsv($arr))); 
    ob_start();
    ?> 
    --<?php echo $random_hash; ?>  
    Content-Type: text/plain; charset=ISO-8859-1; format=flowed
    Content-Transfer-Encoding: 7bit

    Hello World!!! 
    This is simple text email message. 

    --<?php echo $random_hash; ?>  
    Content-Type: application/vnd.ms-excel;
     name="test.csv"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;
     filename="test.csv"

    <?php echo $attachment; ?> 
    --<?php echo $random_hash; ?>-- 

    <?php 
    $message = ob_get_clean(); 
    $mail_sent = @mail( $to, $subject, $message, $headers ); 
}

$array = array(array(1,2,3,4,5,6,7),array(1,2,3,4,5,6,7),array(1,2,3,4,5,6,7));

send_mail($array);
?>

注: 選択の余地がないメール機能を使用する必要があり (ラッパーを使用することもできますが、使用したくない)、サーバー側でファイルを保存できません。

4

4 に答える 4

32

CSV 作成コードを 1 つの関数にラップすることで、はるかに短く効率的な方法で簡単に行うことができます。

CSV ファイルの正しい MIME タイプはtext/csv. また、文字列の連結と明示的な\r\nシーケンスを使用する必要があります。RFC では CRLF の行区切りが必要であり、リテラルの改行でヒアドキュメント/ナウドキュメント/出力バッファリングを使用すると、2 つの問題が発生します。

  1. あなたのインデントはメッセージフォーマットを台無しにするかもしれません
  2. ASCII モードで FTP 経由でファイルをコピーすると、行末が壊れる場合があります

代わりにこれを試してください:

function create_csv_string($data) {

  // Open temp file pointer
  if (!$fp = fopen('php://temp', 'w+')) return FALSE;

  // Loop data and write to file pointer
  foreach ($data as $line) fputcsv($fp, $line);

  // Place stream pointer at beginning
  rewind($fp);

  // Return the data
  return stream_get_contents($fp);

}

function send_csv_mail ($csvData, $body, $to = 'youraddress@example.com', $subject = 'Test email with attachment', $from = 'webmaster@example.com') {

  // This will provide plenty adequate entropy
  $multipartSep = '-----'.md5(time()).'-----';

  // Arrays are much more readable
  $headers = array(
    "From: $from",
    "Reply-To: $from",
    "Content-Type: multipart/mixed; boundary=\"$multipartSep\""
  );

  // Make the attachment
  $attachment = chunk_split(base64_encode(create_csv_string($csvData))); 

  // Make the body of the message
  $body = "--$multipartSep\r\n"
        . "Content-Type: text/plain; charset=ISO-8859-1; format=flowed\r\n"
        . "Content-Transfer-Encoding: 7bit\r\n"
        . "\r\n"
        . "$body\r\n"
        . "--$multipartSep\r\n"
        . "Content-Type: text/csv\r\n"
        . "Content-Transfer-Encoding: base64\r\n"
        . "Content-Disposition: attachment; filename=\"file.csv\"\r\n"
        . "\r\n"
        . "$attachment\r\n"
        . "--$multipartSep--";

   // Send the email, return the result
   return @mail($to, $subject, $body, implode("\r\n", $headers)); 

}

$array = array(array(1,2,3,4,5,6,7), array(1,2,3,4,5,6,7), array(1,2,3,4,5,6,7));

send_csv_mail($array, "Hello World!!!\r\n This is simple text email message.");
于 2012-04-26T14:11:53.963 に答える
2

これは、phpmailer で添付ファイルを電子メールで送信するために使用する csv を作成するためのより簡単なソリューションです。

$csvinfo .= "$row[0],$row[1],$row[2],$row[3]\n";
$attachment = "details.csv";  
file_put_contents($attachment, $csvinfo, LOCK_EX);

および添付ファイル付きの電子メールを送信するための関連する phpmailer 行

$mail = new PHPMailer;
$mail->isSMTP();             // Set mailer to use SMTP
$mail->Host = 'x';           // Specify main and backup SMTP servers
$mail->SMTPAuth = true;       // Enable SMTP     authentication
$mail->Username = 'xx';       // SMTP username
$mail->Password = 'xx';         // SMTP password
$mail->SMTPSecure = 'tls';     // Enable TLS or SSL also accepted
$mail->Port = 587;               // TCP port to connect to
$mail->setFrom('me@madein.us', 'Lily');
$mail->AddAddress("you@madein.us");
$mail->addAttachment($attachment);         // Add attachments
$mail->isHTML(true);             // Set email format to HTML
$mail->Subject = "Report";
$mail->Body    = $message;

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
于 2016-08-24T20:30:41.050 に答える