通过电子邮件将MySQL数据作为CSV文件发送

时间:2018-10-01 13:35:53

标签: php phpmailer

我有以下代码片段,除了一个我无法破解的错误以外,其他都可以正常运行。

这里发生两件事,一件将mySQL数据转换为CSV并通过电子邮件发送给特定用户(工作正常),并在成功/失败后回显消息。 (错误所在)。

运行此命令时,会生成带有正确信息的电子邮件,但我还看到每次将回显消息也下载到CSV文件中。

您能否建议我如何确保回显消息不会以CSV文件的形式下载?

代码如下:

if(isset($_POST['sendmail'])) {
    $emailtosend = $_POST['emailadd'];
    $conn = mysqli_connect('localhost','root','','sample');
    header ('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');
    $filename = 'data.csv';
    $output = fopen($filename, 'w');
    fputcsv($output, array('ID','Product name','Product code', 'Unit price', 'Inventory')); // 
    $query = "SELECT * from products";
    $result = mysqli_query($conn, $query);
    while($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, $row);
    }

    require 'PHPMailerAutoload.php';

    $mail = new PHPMailer;

    $mail->isSMTP();                                      
    $mail->Host = 'smtp.gmail.com';  
    $mail->SMTPAuth = true;
    $mail->Username = 'someone@gmail.com';                 
    $mail->Password = 'password';                           
    $mail->SMTPSecure = 'tls';                            
    $mail->Port = 587;                                    

    $mail->setFrom('one_other@gmail.com', 'Mailer');
    $mail->addAddress($emailtosend, 'Joe User');    
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addAttachment($filename);
    $mail->isHTML(true);                                
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if(!$mail->send()) {
        echo 'Message could not be sent.  Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    fclose($output);
}

第一次尝试,欣赏您的想法!

编辑

$filename = 'data.csv';更改为$filename = tempnam('/tmp', 'data_').'.csv';,如@johannes突出显示

3 个答案:

答案 0 :(得分:1)

您应该在csv数据的while循环之后使用fclose()。

答案 1 :(得分:0)

添加一行以发送标题以澄清内容:

header("Content-Type: text/html; charset=utf-8");

答案 2 :(得分:0)

您可以尝试以下代码。它对我有用。

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'databasename');
if (!$con)
{
    die("error" . mysqli_connect_error());
}

error_reporting(E_ERROR);
$filename = "adhaar_info";
$sql = mysqli_query($con, "SELECT * FROM adhaar_info order by id desc limit 0,10");
$row = mysqli_fetch_assoc($sql);
$filename2='datas/'.$filename.'.csv';
$fp = fopen($filename2, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value){$seperator .= $comma . '' . str_replace('', '""', $name);$comma = ",";}
$seperator .= "\n";
$seperator;
fputs($fp, $seperator);
mysqli_data_seek($sql, 0);
while ($row = mysqli_fetch_assoc($sql))
{
    $seperator = "";
    $comma = "";
    foreach ($row as $name => $value){$seperator .= $comma . '' . str_replace('', '""', $value);$comma = ",";}
    $seperator .= "\n";
    fputs($fp, $seperator);
}

fclose($fp);

$my_file = $filename2;
$path = "datas/";
$from_name = "solomon";
$from_mail = "pss@gmail.com";
$mailto = "pssworkcse@gmail.com";
$subject = "This is a mail with attachment.";
$message = "Hi,\r\n do you got attachment?\r\n\r\Solomon";
$replyto = "pssworkcse@gmail.com";
$file = $my_file;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$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=\"" . $filename2 . "\"\r\n"; 
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"" . $filename2 . "\"\r\n\r\n";
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
mail($mailto, $subject, "", $header)

?>