How to convert CSV file into Excel? - php

I want to export data from the database into an Excel file, then send it directly to an email using phpmailer without saving it to my computer first.
I have done it successfully, but all I can get is the CSV file, whereas I want the Excel file, so is there any way to make the CSV into xlsx?
public function SendEmail() {
$mail = new PHPMailer(true);
try {
$filename = "hoursandpay.csv";
header('HTTP/1.1 200 OK');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=$filename');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$output = fopen($filename, 'w');
fputcsv($output, array('Nik', 'Nama', 'Line', 'Absen'));
$koneksi = mysqli_connect("host", "user", "pass", "database");
$data = mysqli_query($koneksi, "query");
while ($row = mysqli_fetch_assoc($data)) {
fputcsv($output, $row);
}
//Server settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'user#gmail.com';
$mail->Password = 'password';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
//Send Email
$mail->setFrom('from#gmail.com');
//Recipients
$mail->addAddress('to#gmail.com');
$mail->addAddress('to2#gmail.com');
$mail->addAddress('to3#gmail.com');
$datetime = new DateTime("now", new DateTimeZone("Asia/Jakarta"));
$today = $datetime->format('Y-m-d H:i:s');
//Content
$mail->isHTML(true);
$mail->Subject = 'LAPORAN EMAIL TANGGAL ' . $today;
$mail->Body = 'ABSENSI';
$mail->addAttachment($filename);
$mail->send();
unlink($filename);
fclose($output);
echo $this->session->set_flashdata('sukses', 'Kirim email sukses');
} catch (Exception $ee){
echo $this->session->set_flashdata('message', $ee->getMessage());
}
redirect(base_url());
}
Or is there a way to export from database to Excel and then send it directly to email without saving it first? Because all I can get is with the vsc file

Related

How to send downloaded excel file to mail using phpMailer liabrary?

I have a code that generates excel file from mysql database and downloads the file. I want to send that file in my email after the file is downloaded. I am using PHPMailer liabrary for doing this. I tested PHPMailer module individually its working fine, the mail is going but when i attached that module with my existing code where the excel file is downloading its not working as intended. It gives me error "The site can't be reached." If i remove the attchment line from my code it works fine. The file is downloaded and the mail is sent. But i want that file to be attached in my email. Here is my code i'm using
<?php
require("PHPMailer/src/SMTP.php");
require("PHPMailer/src/PHPMailer.php");
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer();
$conn = new mysqli('localhost', 'root', 'root');
mysqli_select_db($conn, 'dailyplay');
$setSql = "SELECT id, name, description FROM genres";
$setRec = mysqli_query($conn, $setSql);
$columnHeader = "ID"."\t"."Name"."\t"."Description";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=INTRANSIT_Report.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
sleep(5);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'USERNAME_HERE';
$mail->Password = 'PASSWORD_HERE';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
//Recipients
$mail->setFrom('EMAIL_HERE', 'USERNAME_HERE');
$mail->addAddress('RESIPIENT_HERE', 'USERNAME_HERE');
$mail->addAttachment('/home/winningcodie/Downloads/INTRANSIT_Report.xls', 'Report.xls');
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
Rest of the code is working fine. The file is downloaded in excel format. If i uncomment the attachment line of mail it gives me the error "The site can't be reached".
You generate the file dynamically and send it to the browser, which saves it on the same disk, while the script tries to read the file as part of the same process - I'm afraid it won't work (and as you can see it doesn't).
Don't send the file to the browser right away. Save it on disk first and then read it for the e-mail sending process and then return it to the browser.
Try this :
<?php
require("PHPMailer/src/SMTP.php");
require("PHPMailer/src/PHPMailer.php");
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer();
$conn = new mysqli('localhost', 'root', 'root');
mysqli_select_db($conn, 'dailyplay');
$setSql = "SELECT id, name, description FROM genres";
$setRec = mysqli_query($conn, $setSql);
$columnHeader = "ID"."\t"."Name"."\t"."Description";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=INTRANSIT_Report.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
sleep(5);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'USERNAME_HERE';
$mail->Password = 'PASSWORD_HERE';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
//Recipients
$mail->setFrom('EMAIL_HERE', 'USERNAME_HERE');
$mail->addAddress('RESIPIENT_HERE', 'USERNAME_HERE');
$mail-move_uploaded_file('/home/winningcodie/Downloads/INTRANSIT_Report.xls',"uploads/INTRANSIT_Report.xls");
$mail->addAttachment("uploads/INTRANSIT_Report.xls", 'Report.xls');
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>

Getting junk characters in email subject while using PHPMailer. How to fix this?

I am using PHPMailer 5.1, and while sending email through PHPMailer, I get few junk characters like =?UTF-8?Q??=, and not the expected text in subject.
Here is the my code which I used:
$recipient = 'xxx#xxx.cz';
$sender = 'xxx#xxx.cz';
header("Access-Control-Allow-Origin: *");
try
{
if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
{
throw new ErrorException('Method Not Allowed (please use POST)', 405);
}
$data = unserialize(base64_decode($_POST['_data']));
$_POST = unserialize(base64_decode($_POST['_post']));
ob_start();
$cislo_objednavky = 1 + (int)
file_get_contents('cpo/cpo.txt');
require 'tabulka.php';
$body = ob_get_contents();
ob_end_clean();
require 'phpmailer/class.phpmailer.php';
$mail = new PHPMailer(TRUE);
$mail->CharSet = 'UTF-8';
$mail->Host = "xxx.xxxx.cz";
$mail->SMTPAuth = true;
$mail->Port = 25;
$mail->Username = "xxx#xxx.cz";
$mail->Password = "xxxxx";
$mail->Encoding = 'base64';
$mail->AddAddress($recipient);
$mail->SetFrom($sender, 'XXXXXX');
$mail->AddReplyTo($sender);
$mail->AddCC($_POST['email']);
$mail->Subject = ('Objednávka č.'.$cislo_objednavky);
$mail->MsgHTML('html tělo mailu');
$mail->Send();
file_put_contents('xxxx.xxx', $cislo_objednavky);
}
catch (Exception $e)
{
header('HTTP/1.0 '.$e->getCode().' '.$e->getMessage());
echo '<h1>'.($e->getMessage().' (#'.$e->getCode().')').'</h1>';
exit;
}
What is the problem here?
Thank you so much.

multiple attachments going with single mail from phpmailer

I am sending payslip mails with payslips as attachment with phpmailer class. the problem is the first mail is going with one attachment but the sedonf mail is going with the first and the second attachments together.
For example:
mail for employee name : A is going with A.pdf
mail for employee name : B is going with A.pdf and B.pdf
need some help. my project completion date is tomorrow and I am stuck in this last problem.
this is my code:
<?php
require_once 'mailerClass/PHPMailerAutoload.php';
require_once '../connect.php';
$mail = new PHPMailer;
//$mail->isSMTP();
$sql = "SELECT * FROM mail ORDER BY Id";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($query, MYSQL_ASSOC)){
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = false;
$mail->Username ='riteshrc13#gmail.com';
$mail->Password = "password";
$mail->setFrom('64mediakraft#gmail.com', 'Mediakraft');
$mail->addAddress($row['Email'], $row['Name']);
$mail->Subject = "Payslip of " . $row['Name'];
$mail->Body = "payslip email";
$mail->AltBody = 'Payslip Email for the month. Please find the payslip attached.';
$mail->isHTML(true);
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$pdf = "C:/Reports/" . $row['Name']. ".pdf";
$mail->addAttachment($pdf);
if ($mail->send()) {
echo "<script>alert('Mail Sent success');</script>";
// header("Location:index.php");
}
else {
echo "<script>alert('Mailer Error: ' $mail->ErrorInfo);</script>";
// header("Location: index.php");
}
$pdf = "";
} //endwhile
?>
Creating a new instance inside the loop will work, but it's very inefficient and means you can't use keepalive, which makes a huge difference to throughput.
Base your code on the mailing list example provided with PHPMailer which shows how to send most efficiently, and read the docs on sending to lists. To paraphrase that example, it should go roughly like this:
$mail = new PHPMailer;
//Set properties that are common to all messages...
$mail->isSMTP();
$mail->SMTPKeepAlive = true;
$mail->Host = 'mail.example.com';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Subject = 'Hello';
$mail->From = 'user#example.com';
//etc
//Loop over whatever resource gives you your recipients
foreach ($result as $target) {
//Set properties that are specific to this message
$this->addAddress($target['email']);
$this->addAttachment($target['file']);
//Send the message
$this->send();
//All done, so clear recipients and attachments for next time around
$mail->clearAddresses();
$mail->clearAttachments();
}
Don't forget to add some error checking in there, and I can also see that you're using an old version of PHPMailer - so get the latest, and base your code on the mailing list example.
$mail = new PHPMailer; // this should be inside of while, I think...
Thanks to #jonStirling and #toor for the help.
complete working code for other help seekers:
<?php
require_once 'mailerClass/PHPMailerAutoload.php';
require_once '../connect.php';
//$mail->isSMTP();
$counter = 1;
$sql = "SELECT * FROM mail ORDER BY Id";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($query, MYSQL_ASSOC)){
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = false;
$mail->Username ='riteshrc13#gmail.com';
$mail->Password = "password";
$mail->setFrom('64mediakraft#gmail.com', 'Mediakraft');
$mail->addAddress($row['Email'], $row['Name']);
$mail->Subject = "Payslip of " . $row['Name'];
$mail->Body = "payslip email";
$mail->AltBody = 'Payslip Email for the month. Please find the payslip attached.';
$mail->isHTML(true);
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$pdf = "C:/Reports/" . $row['Name']. ".pdf";
$mail->addAttachment($pdf);
if ($mail->send()) {
echo "<script>alert('Mail Sent success');</script>";
// header("Location:index.php");
}
else {
echo "<script>alert('Mailer Error: ' $mail->ErrorInfo);</script>";
// header("Location: index.php");
}
$pdf = "";
$mail->clearAttachments();
} //endwhile
?>

How to send xml (like attachment) in phpMailer

$myXML =
'<?xml version="1.0" encoding="ISO-8859-2"?>
<Document-ORDRES>
<ORDRES-Header>
<OrderResponseNumber>123</OrderResponseNumber>
<OrderResponseDate>0</OrderResponseDate>
<BuyerOrderNumber>0</BuyerOrderNumber>
<BuyerOrderDate>0</BuyerOrderDate>
<DeliveryDate>0</DeliveryDate>
</ORDRES-Header>
</Document-ORDRES>';
$xml=simplexml_load_string($myXML) or die("Error: Cannot create object");
public function send_mail($xml){
print_r($xml);
echo "</br></br>";
$data;
require 'C:\xampp\htdocs\PHPMailer-master\PHPMailerAutoload.php';
header('Content-Type: text/html; charset=utf-8');
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "...";
$mail->Port = 587;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPAuth = true;
$mail->Username = "...";
$mail->Password = "...";
$mail->setFrom('...', '...');
$mail->addAddress('...', '');
$mail->Subject = '...';
$mail->AltBody = " ";
$mail->msgHTML("Test");
$mail->addAttachment($xml, "xml.xml");
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
Can you tell me what should I do?
I want send this xml like attachment, but in mail I haven't got attachments.
I've got just e-mail text.
Use addStringAttachment() method instead of addAttachment():
$mail->addStringAttachment($xml, "xml.xml");
addAttachment() adds attachment with path to a file, so alternatively you would have to save the xml as a file:
$file = __DIR__ . '/xml.xml';
file_put_contents($file, $myXML);
then add it and delete it...
$mail->addAttachment($file);
$mail->send();
unlink($file);

Page not redirecting

An Excel file is uploaded from a html form the regno and email information are read from the excel file.Each user is then sent an email along with a message.The regno and email are inserted in the database.
gmail is used for sending emails $frmid is the from email address and $password is the password for it.
Here is the code.
<?php
require_once("function/PHPExcel/Classes/PHPExcel/IOFactory.php");
require_once("function/Mail/class.phpmailer.php");
require_once("function/connection.php");
if($_SERVER['REQUEST_METHOD']=='POST' && is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
$msg=$_POST['msg'];
$arr=array();
$frmid=htmlspecialchars(trim($_POST['frm_id']),ENT_QUOTES,'UTF-8');
$password=htmlspecialchars(trim($_POST['password']),ENT_QUOTES,'UTF-8');
$subject=htmlspecialchars(trim($_POST['subject']),ENT_QUOTES,'UTF-8');
$name=$_FILES['uploaded_file']['tmp_name'];
try {
$inputFileType = PHPExcel_IOFactory::identify($name);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($name);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
for ($row = 1; $row <= $highestRow; $row++){
$email = $sheet->getCell('B'.$row )->getValue();
$regno = strtoupper($sheet->getCell('A'.$row )->getValue());
$arr[]=array($regno,$email);
$message=$msg;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->IsHTML(true);
$mail->Username = $frmid;
$mail->Password = $password;
$mail->SetFrom($frmid);
$mail->Subject = $subject;
$mail->MsgHTML($msg);
$mail->AddAddress($email);
if(!$mail->Send()){
die("Failed to send to Email Id ".$email."\n<br/>");
}
}
} catch(Exception $e) {
die('Server Error');
}
$db=connection();
$query="INSERT INTO table(regno,email) VALUES ";
$query=buildinsert($query,$highestRow);
$stmt=$db->prepare($query);
$result=$stmt->execute($arr);
if($stmt->rowCount()==$highestRow){
redirect("page.php?result=1");
}else{
redirect("page.php?result=0");
}
}
?>
The functions used are
<?php
function buildinsert($query,$rows){
$placeholder=array();
for($i=0;$i<$rows;$i++){
$placeholder[]="(?,?)";
}
return($query.implode(",",$placeholder));
}
function connection(){
try{
return (new PDO("mysql:host=localhost;dbname=dbms,","root","passwd"));
}catch(Exception $e){
die( "An error occured".$e->getMessage());
}
}
function redirect($link){
header("Location:".$link);
}
?>
The problem is I`m not being redirected after the operation completes.The mails are sent successfully and the content is also added but the page does not change.I get same page as before
Found the Problem.The phpmailer,phpexcel are fine the problem was with connection.php
After I added buildinsert function I left a newline,The page was not redirecting because of the newline space between
Thanks Jon!

Categories