-1

Ive been on this for a while. What I am trying to do is create a CSV file from the while loop with CODE & QUANTITY then attach it to the email below then send. Any help would be greatly appreciated

$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);    

I want it to look something like this. The .csv file will be an attachment and Ill still display the regular email below it.

enter image description here

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
BTR383434
  • 3
  • 3
  • You want to attach it as file like .csv or just plain text? – Jwan Mar 27 '21 at 21:35
  • attach it as a .csv file to download in the email. I still want the regular html email to display but with the file as an attachment. – BTR383434 Mar 27 '21 at 21:46

1 Answers1

0

Here you go. But You need the 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;


Jwan
  • 177
  • 3
  • 12