How to send an email with a excel attachment - php

i am saving excel in folder in my server(note excel is saving in server),i am trying to sent email with an excel attachment that saved in my server,but i didn't receive an email with the attachment(i.e: i received email without an attachment),below is my code please guide me how to do it.
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('/data/data/www/ms/pricelists/newxcelexample.xls');
$my_path ="/data/data/www/ms/pricelists/newxcelexample.xls";
include "class.phpmailer.php"; // include the class file name
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
//$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "mail.xichlomobile.com";
$mail->Port = "25"; // or 587
$mail->IsHTML(true);
$mail->Username = "************";
$mail->Password = "**********";
$mail->SetFrom("**************");
$mail->Subject = Test;
$mail->Body = "Test";
$mail->AddAddress("*********");
$mail->AddAttachment($my_path);
if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}
else{
echo "<span style='font-size:45px;color:#000000;'>Message has been sent</span><br><br>";
}

Have you controlled that the file is really present and gets saved correctly? Has the web server the right do read the file (normally readable by the user www-data)?
Perhaps try to supply also the filename to AddAttachment:
$mailer->AddAttachment($my_path, basename($my_path));
// or
$mailer->AddAttachment($my_path, basename($my_path), "quoted-printable", "application/vnd.ms-excel") ;
If you're using a newer version of PHPMailer, you can also use exceptions to see what's happening. Perhaps it isn't preventing the mail from going out but from attaching the file.
try {
// preparing the email just before the mail->Send()
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Try sending another file for once, e.g. a *.txt or *.zip (to check if you have limitations on the file types you can send, which would be unlikely for a excel file).

Related

PHPMailer + HTML2PDF: pdf invalid and pj

Good morning all ,
I would like to attach a PDF created following a form with HTML2PDF then send it with PHMailer.
Everything works, the email goes well, I managed to create the PDF by saving it on my hard drive.
But when I try to attach it to my email, the pdf is fine in pj but I can't open it.
enter image description here
It is the same size of my locally created pdf.
I followed the tutorial and wiki of the two libraries, well I think ^^
Here is my PHPMailer code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require './vendor/phpmailer/phpmailer/src/Exception.php';
require './vendor/phpmailer/phpmailer/src/PHPMailer.php';
require './vendor/phpmailer/phpmailer/src/SMTP.php';
require './vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = '******'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '*****'; // SMTP username
$mail->Password = '*****'; // SMTP password
//$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = ****; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('****#****.com', '****');
$mail->addAddress($to); // Add a recipient
//$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo($shop_email, 'Votre magasin');
//$mail->addCC('cc#example.com');
$mail->addBCC($shop_email);
// Attachments
$mail->addStringAttachment($pdf_done, 'myPdf.pdf'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
$mail->send();
echo '';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
and here is the code for HTML2PDF:
ob_start();
// --> mon code HTML de creeation du PDF
$content = ob_get_clean();
require_once dirname(__FILE__).'/../vendor/autoload.php';
use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;
try{
$pdf = new \Spipu\Html2Pdf\Html2Pdf('P', 'A4', 'fr');
$pdf->writeHTML($content);
$pdf_done = $pdf->output('myPdf.pdf', 'S');
}catch(\Spipu\Html2Pdf\Exception\Html2PdfException $e){
die($e);
}
?>
I tried adding ", 'base64', 'application / pdf'" in the addStringAttachment but it doesn't change anything.
Do you have any idea of my mistake?
Thank you all
Debug one thing at a time. First download the PDF manually and make sure it looks correct – if the PDF is bad to start with, emailing it isn't going to improve things. Next check that it is readable from PHP – for example serve it using readfile(). Then when you try to attach it, check the return value of your call to addAttachment() like this:
if (!$mail->addAttachment('/path/to/myPdf.pdf')) {
die('could not read PDF');
}
Also note the difference between addAttachment and addStringAttachment; you're adding a file that's been saved to disk, so you want the first one, not the second.

PHPMailer send() function crashes on live server but not XAMPP

I have been reading through SO trying to find an answer to my PHPMailer issue.
I am using the latest PHPMailer code and I have my code in a try and catch block. I am using the same SMTP credentials on both the XAMPP hosted site and the 1&1.co.uk hosted site. I have also tried printing debug to a file and know the script gets as far as the $mail->send() section, but then all I get back is a page saying:
The www.reasonstobejolly.com page isn’t working
www.reasonstobejolly.com didn’t send any data.
No exceptions or anything thrown. Can anyone explain why this isn't working?
require '../../../PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'auth.smtp.1and1.co.uk'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '##########'; // SMTP username
$mail->Password = '##########'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('orders#reasonstobejolly.com', 'Orders at Reasons to be Jolly');
$mail->AddAddress($email, $firstName." ".$lastName); // Add a recipient
$mail->addReplyTo('enquiries#reasonstobejolly.com', 'Order Enquiry');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = "Your Order Has Been Received";
$mail->Body = "Dear ".$firstName." ".$lastName."<br/>"
. "Your order has been received; it will be processed as soon as possible and should be with you in the timeframe specified in our shipping guidelines.<br/>
";
if (isset($randomPassword)) {
$mail->Body .= "<p>Username: $email</p><p>Password: $randomPassword</p>";
}
$mail->Body .= "<p>Order Reference : $transactionId<br/>
Order Date : ".date('d-m-Y H:i:s', strtotime($orderTime))."</p>
<p>BILL TO:<br/>
$shipToName <br/>
$shipToStreet<br/>
$shipToCity<br/>
$shipToState<br/>
$shipToZip<br/>
</p>
<p>
DELIVER TO:<br/>
$shipToName <br/>
$shipToStreet<br/>
$shipToCity<br/>
$shipToState<br/>
$shipToZip<br/>
</p>
<table>
<tr><td>Qty</td><td>Description</td><td>Price</td></tr>";
$orderOverviewID = getOrderOverviewIDByPayPalReference($transactionId);
$orderItemsArray = getItemsByOrderOverviewID($orderOverviewID);
$postage = 0;
foreach ($orderItemsArray as $id => $order) {
$productEmail = getProductByProductID($order->productID);
$postageAmount = getPostageByPostageID($productEmail->postageID);
$mail->Body .= "<tr><td>".$order->itemQuantity."</td>"
. "<td>".$productEmail->productName."</td>"
. "<td>£". (getDimensionByID(getColourByID($order->colourID)->dimensionID)->dimensionPrice) * $order->itemQuantity."</td></tr>";
if ($postageAmount->postagePrice > $postage) {
$postage = $postageAmount->postagePrice;
}
}
// these are from create invoice.
$vat = $amt * 0.2;
$subtotal = $amt - $postage;
// TODO VAT and postage need to be calculated in the Paypal bit.
$mail->Body .= "<tr><td></td><td align='right'>Sub Total:</td> <td>£$subtotal</td></tr>
<tr><td></td><td align='right'>Standard Delivery:</td><td>£$postage</td></tr>
<tr><td></td><td align='right'>(Including VAT # 20%):</td><td>£$vat</td></tr>
<tr><td></td><td align='right'>GRAND TOTAL:</td><td>£$amt</td></tr>
</table>
If you have a query, or require further information, please contact Customer Service at: http://www.reasonstobejolly.com";
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Turns out after a phone call to 1and1.co.uk, that the only mail option they support is mail(). They told me that PHPMailer will not work on their servers.

PHP Mailer -> PDF to Email provides blank PDF as attachment

I am using PHP Mailer to basically send a interactive PDF to an email address. This works locally calling the script from the PDF to the server, but does not work when the PDF is completed on the server.
Code is below:
<?php
if(!isset($HTTP_RAW_POST_DATA)) {
echo "The Application could not be sent. Please save the PDF and email it manually.";
exit;
}
echo "<html><head></head><body><img src='loading.gif'>";
//Create PDF file with data
$semi_rand = md5(time());
$pdf = $HTTP_RAW_POST_DATA;
$file = $semi_rand . ".pdf";
$handle = fopen($file, 'w+');
fwrite($handle, $pdf);
fclose($handle);
//
require_once('class/class.phpmailer.php');
include("class/class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(false); // the true param means it will throw exceptions on errors, which we need to catch
$mail -> CharSet = "UTF-8";
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "HOST"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "HOST";
$mail->Port = 465;
$mail->Username = "USERNAME";
$mail->Password = "PASSWORD";
$mail->AddAddress('TO ADDRESS');
$mail->SetFrom('FROM ADDRESS');
$mail->Subject = 'SUBJECT';
$mail->Body = 'Please see attachment';
$mail->IsHTML(true);
$mail->AddAttachment($file); // attachment
$mail->Send();
//Delete the temp pdf file then redirect to the success page
// unlink($file);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL="1.1.1.1">';
exit;
} catch (phpmailerException $e) {
//you can either report the errors here or redirect them to an error page
//using the above META tag
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
//Verify the temporary pdf file got deleted
unlink($file);
?>
Is there something I am missing? All values for the $mail (host, username, password etc) are correct - but when it creates the PDF to send, it only comes through as < 1kb. My PDF calls this PHP file on submit.
You can't create PDFs like simple txt or csv files with fwrite. It is a more sophisticated file type.
Look into DomPDF which for your setting may look somewhat like the below (assuming $HTTP_RAW_POST_DATA is an html document):
require("dompdf_config.inc.php");
$semi_rand = md5(time());
$pdf = file_get_contents('http://www.pdfpage.com/');
$file = $semi_rand . ".pdf";
$dompdf = new DOMPDF();
$dompdf->load_html($pdf);
$dompdf->set_paper('a4', 'portrait');
$dompdf->render();
$dompdf->stream($file, array('Attachment' => '0'));
...
// USE $file as needed in email attachment

AddStringAttachment with PDF in PHPMailer not work

I had used phpmailer for send email. Now i have to attach pdf file in email. It attached pdf but that pdf could not open. and is shows there is problem in format. Is AddStringAttachment doesn't work for pdf? What should i do?
require_once('././php_mailer/class.phpmailer.php');
$this->load->helper('mail_html');
$body2 = "You are receiving this email because the Transfer Application submitted for transferring to g is missing required documentation.
Please see the note below for details. The transfer application will not be reviewed until all of the necessary materials are received by the UHSAA.
";
$body = 'test';
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = 'smtp.gmail.com'; // SMTP server
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com'; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = 'nabina.smartmobe#gmail.com'; // SMTP account username
$mail->Password = '*******'; // SMTP account password
$mail->AddAddress('nabina.shahi#gmail.com','nabina');
$mail->SetFrom('no-reply#nayacinema.com.np', 'no-reply#nayacinema.com.np');
$mail->AddReplyTo('no-reply#nayacinema.com.np', '');
$mail->IsHTML(true);
$mail->Subject ='NayaCinema: Test';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
$mail->AddStringAttachment($body2, 'Filename.pdf', 'base64', 'application/pdf');
if($mail->Send()){
echo 'sent'; die;
return true;
}else{
echo ' not sent'; die;
return false;
}
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Thank you
You can create a .pdf with another PHP class TCPDF. You can see how it goes in examples. And if you dont want to save the PDF in the server you can send like you did, you only need to change the output line of the TCPDF $pdf->... codes, like this:
$attachdata = $pdf->Output('foo.pdf','S'); // return the document as a string (name is ignored)
then you can send it:
$mail->AddStringAttachment($attachdata, 'Filename.pdf');

PHPMailer not sending CC or BCC

I have been testing the following code for hours. The email will send to the addresses added through $mail->AddAddress() and in the received email it states the cc but the person cced does not receive the email. I have looked everywhere and can not find a solution to why this is happening. I have run tests and all variables are being submitted to this code properly.
My server is running Linux Red Hat
My Code:
require_once('../smtp/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "tls"; // sets the prefix to the server
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = $port; // set the SMTP port for the GMAIL server 465 or 587
$mail->Username = $username; // GMAIL username
$mail->Password = $password; // GMAIL password
// Add each email address
foreach($emailTo as $email){ $mail->AddAddress(trim($email)); }
if($cc!=''){ foreach($cc as $email){ $mail->AddCC(trim($email)); } }
if($bcc!=''){ foreach($bcc as $email){ $mail->AddBCC(trim($email)); } }
$mail->SetFrom($emailFrom, $emailName);
$mail->AddReplyTo($emailFrom, $emailName);
$mail->Subject = $subject;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($content);
// $mail->AddAttachment('images/phpmailer.gif'); // attachment
// $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo'1';exit();
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Old question, but I ended up here looking for an answer. Just learned elsewhere that those functions AddCC and AddBCC only work with win32 SMTP
Try using:
$mail->addCustomHeader("BCC: mybccaddress#mydomain.com");
See http://phpmailer.worxware.com/?pg=methods
Hope this helps someone, cheers!
$address = "xxxxx#gmail.com";
$mail->AddAddress($address, "technical support");
$address = "yyyyyy#gmail.com";
$mail->AddAddress($address, "other");
$addressCC = "zzzzzz#gmail.com";
$mail->AddCC($addressCC, 'cc account');
$addressCC = "bcc#gmail.com";
$mail->AddBCC($addressCC, 'bcc account');

Categories