【问题标题】:How do you create a csv file from a while loop and attach it to an email in php? [duplicate]如何从 while 循环创建 csv 文件并将其附加到 php 中的电子邮件? [复制]
【发布时间】:2021-03-29 01:40:28
【问题描述】:

我已经有一段时间了。我要做的是使用 CODE & QUANTITY 从 while 循环创建一个 CSV 文件,然后将其附加到下面的电子邮件中,然后发送。任何帮助将不胜感激

$sql = mysql_query("SELECT code, quantity 
                    FROM table 
                    WHERE active = '1' 
                    ORDER BY code Asc");

while($row = mysql_fetch_array($sql)){
    $code = $row['code'];
    $quantity = $row['quantity'];   
    //CREATE CSV FILE HERE I THINK?
}


$to = “email@gmail.com” ;
$from = “email@website.com”;
$subject = “Inventory”;
$message = ''<html>Code</html>'';    

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Inventory' . "\r\n";
      
mail($to, $subject, $message, $headers);    

我希望它看起来像这样。 .csv 文件将是一个附件,我仍会在其下方显示常规电子邮件。

【问题讨论】:

  • 您想将其附加为 .csv 等文件还是纯文本?
  • 将其附加为 .csv 文件以在电子邮件中下载。我仍然希望显示常规的 html 电子邮件,但将文件作为附件。

标签: php


【解决方案1】:

给你。但是您需要 PHPMailer。 Learn how to set up PHPMailer on shared hosting

function create_cvs_from_db($sql)
{
    // create a temp location in memory with 5MB
    $csv = fopen('php://temp/maxmemory:' . (5 * 1024 * 1024), 'r+');

    // add the headers
    fputcsv($csv, array("code", "quantity"));
    // the loop
    while ($row = mysql_fetch_array($sql)) {
        $code = $row['code'];
        $quantity = $row['quantity'];
        // creates a valid csv string
        fputcsv($csv, array($code, $quantity));

    }

    rewind($csv);
    // return the the written data
    return stream_get_contents($csv);

}

// you need to setup PHPMailer
$mail = new PHPMailer();

// configurations

$mail->isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = '1a2b3c4d5e6f7g'; //your mail username
$mail->Password = '1a2b3c4d5e6f7g'; //your mail password
$mail->SMTPSecure = 'tls';
$mail->Port = 2525;


// now the fun part
$mail->setFrom('info@mailtrap.io', 'Mailtrap');
// the subject of the email
$mail->Subject = 'Test Email via Mailtrap SMTP using PHPMailer';
// if your mail body uses html
$mail->isHTML(true);
$mailContent = "";
$mail->Body = $mailContent;

/**
 * now here you attach your file
 */
// the cvs extension is very important
$filename = "summary.cvs";
$mail->addStringAttachment(create_cvs_from_db($sql), $filename);

// now send  the mail

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


【讨论】:

  • 你不需要phpMailer来发送附件,这可能会更容易,但你可以手动完成并使用mail()
  • 如何使用邮件附加 csv 文件。我已经搜索了 2 天
  • 我知道他不需要。但是对于我写的是 PHPMailer 是必要的
  • @BTR383434 作为初学者使用PHPMailer。如果你愿意,你可以切换到mail()
  • @BTR383434 无法安装或无法使用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多