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

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}";
}
?>

Related

Could not access file: Could not access file: Could not access file: PHP Mailer issue

Code is working fine without attachments. and attachment code is working fine on another page anybody can help to solve this?
<?php
require('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Username = "info#guildsconnect.org";
$mail->Password = "Guildsconnect";
$mail->Host = "webs10rdns1.websouls.net";
$mail->Mailer = "smtp";
$mail->SetFrom($contact_email, $contact_name);
$mail->AddReplyTo($contact_email, $contact_name);
$mail->AddAddress("hashimbhatti906#gmail.com");
$mail->Subject = $sub1;
$mail->WordWrap = 80;
$mail->MsgHTML($emailbodyis);
foreach ($_FILES["attachment"]["name"] as $k => $v) {
$mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}
$mail->IsHTML(true);
if(!$mail->Send()) {
$_SESSION["error"] = "Problem in Sending Mail.";
} else {
$_SESSION["success"] = "Mail Sent Successfully.";
}
?>
Firstly, you're using a very old and unsupported version of PHPMailer, so upgrade. It also looks like you have based your code on a very old example.
You are not handling the file upload safely, not validating the uploaded file before trying to use it, as per the PHP docs.
PHPMailer provides an example that shows how to handle and upload and attach it correctly. The key parts are to use move_uploaded_file() to validate the upload before using it, and not to trust the supplied filename. To paraphrase the example:
//Extract an extension from the provided filename
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
//Define a safe location to move the uploaded file to, preserving the extension
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name'])) . '.' . $ext;
if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadfile)) {
//Now create a message
$mail = new PHPMailer();
...
//Attach the uploaded file
if (!$mail->addAttachment($uploadfile, 'My uploaded file')) {
$msg .= 'Failed to attach file ' . $_FILES['attachment']['name'];
}
if (!$mail->send()) {
$msg .= 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$msg .= 'Message sent!';
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
You don't need to set Mailer yourself; it's already done for you by isSMTP().

How create an event Calendar outlook PHP

I find the second part (from header to the end) code in a site: it only download a file ics but it doesn't add in my calendar. However the 1st part is about sending mail and it's working !
<?php
$mailSub = "Invitation";
$mailMsg = "Bonjour";
require '../PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer();
$mail->IsSmtp();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.live.com";
$mail->Port = 587; // or 587
$mail->IsHTML(true);
$mail->Username = "**************";
$mail->Password = "*****************";
$mail->setFrom('*****************');
$mail->Subject = $mailSub;
$mail->Body = $mailMsg;
$mail->AddAddress($mailto);
//$mail->Send();
if(!$mail->send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "E-Mail has been sent";
}
header("Content-Type: text/Calendar");
header("Content-Disposition: inline; filename=calendar.ics");
echo "BEGIN:VCALENDAR\n";
echo "VERSION:2.0\n";
echo "PRODID:-//Foobar Corporation//NONSGML Foobar//EN\n";
echo "METHOD:REQUEST\n"; // requied by Outlook
echo "BEGIN:VEVENT\n";
echo "UID:".date('Ymd').'T'.date('His')."-".rand()."-example.com\n"; //required by Outlok
echo "DTSTAMP:".date('Ymd').'T'.date('His')."\n"; // required by Outlook
echo "DTSTART:20180909T000000\n";
echo "SUMMARY:TEST\n";
echo "DESCRIPTION: this is just a test\n";
echo "END:VEVENT\n";
echo "END:VCALENDAR\n";
?>

PHP PDFLIB PHPMAILER Create, Save, Send

i'd like to create a PDF using PDFLIB, saving it to the server, send it to the recipient and open it after all!
With this code I can create it, save it to the server, send it but not display it in browser's pdf application.
Any help on that? Thanks in advance.
<?php
try {
$p = new PDFlib();
/* all strings are expected as utf8 */
$p->set_option("stringformat=utf8");
/* open new PDF file; insert a file name to create the PDF on disk */
if ($p->begin_document("test.pdf", "") == 0) {
die("Error: " . $p->get_errmsg());
}
$p->set_info("Creator", "hello.php");
$p->set_info("Author", "Rainer Schaaf");
$p->set_info("Title", "Hello world (PHP)!");
$p->begin_page_ext(595, 842, "");
$font = $p->load_font("Helvetica-Bold", "unicode", "");
if ($font == 0) {
die("Error: " . $p->get_errmsg());
}
$p->setfont($font, 24.0);
$p->set_text_pos(50, 700);
$p->show("Hello world!");
$p->continue_text("(says PHP)");
$p->end_page_ext("");
$p->end_document("");
//#########################################
//
//############# PHP MAILER ################
echo (extension_loaded('openssl')?'SSL loaded':'SSL not loaded')."\n";
date_default_timezone_set('Etc/UTC');
require 'phpmailer/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
$mail->Host = 'tls://smtp.gmail.com';
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "xxxx.xxxx#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "xxxxxxxxxx";
//Set who the message is to be sent from
$mail->setFrom('xxxxxxx#gmail.com', 'First Last');
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('xxxxxxxx#email.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->Body = 'trying to send a pdf';
//Replace the plain text body with one created manually
//$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('test.pdf');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
$buf = $p->get_buffer();
$len = strlen($buf);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=hello.pdf");
print $buf;
}
}
catch (PDFlibException $e) {
die("PDFlib exception occurred in hello sample:\n" .
"[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .
$e->get_errmsg() . "\n");
}
catch (Exception $e) {
die($e);
}
$p = 0;
?>
Basic HTTP problem. You are outputting text before the headers that identify it as a PDF, which will break it. I expect you're getting errors logged saying "headers already sent" from those calls to header(). Comment out the echo "Message sent!"; line.

PHP attach audio file in email

I'm using the following SMTP mail code to send audio attachment:
<?php
session_start();
$title = $_POST['title'];
$first_name = $_POST['name'];
$last_name = $_POST['lastname'];
$email_from = $_POST['email'];
$scaptcha = strtolower($_POST['scaptcha']);
if ($scaptcha != $_SESSION['captcha']) {
echo 'You have entered wrong captcha';
exit(0);
}
require('./class.phpmailer.php');
function clean_string($string) {
$bad = array("content-type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
$email_message = "";
$email_message .= "Title: " . clean_string($title) . "\n";
$email_message .= "First Name: " . clean_string($first_name) . "\n";
$email_message .= "Last Name: " . clean_string($last_name) . "\n";
$email_message .= "Email: " . clean_string($email_from) . "\n";
$allowedExts = array("mp3","wav","dss");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "audio/mpeg")) && in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "<script>alert('Error: " . $_FILES["file"]["error"] . "')</script>";
} else {
$d = 'Audio/Uploads/';
$de = $d . basename($_FILES['file']['name']);
move_uploaded_file($_FILES["file"]["tmp_name"], $de);
$fileName = $_FILES['file']['name'];
$filePath = $_FILES['file']['tmp_name'];
}
} else {
echo "<script>alert('Invalid file')</script>";
}
$headers = 'From: ' . $email_from . "\r\n" .
'Reply-To: ' . $email_from . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.gmail.com";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "saro17.ams#gmail.com";
$mail->Password = "*****";
$mail->SetFrom($email_from, $first_name . ' ' . $last_name);
//$mail->AddReplyTo('replyto#example.com','First Last');
$mail->AddAddress('saro17.ams#gmail.com', 'Saravana');
$mail->Subject = 'New audio file received';
$mail->MsgHTML($email_message);
$mail->AltBody = 'This is a plain-text message body';
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
if (!$mail->Send()) {
echo "<script>alert('Mailer Error: " . $mail->ErrorInfo . "')</script>";
} else {
echo "<script>alert('Your request has been submitted. We will contact you soon.')</script>";
Header('Location: contact.php');
}
?>
Please help me to fix this. I have been trying this for more than a week. Still I didn't get it. I have tried the PHP mailer also. That also not working.
UPDATE: I'm getting the following error:
Mailer Error: The following From address failed: saro17.ams#gmail.com : Called MAIL FROM without being connected,
send the audio file link in message instead of inline attachment.
$mail->AddAttachment method use for inline attachment.
due to the file encryption and file size , maximum server not allow to send inline attachment of audio, video or zip files.
Well..It's really very easy to attach anything while using PHPMailer.Here is the code :
PHPMailer Link : https://github.com/PHPMailer/PHPMailer
You can add attachments like :
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
While here is full code :
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$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->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}

Error in email attached file as file gets corrupted at receiver side

I am trying to send Email with Attachment using php.
Attachment is sent but attachment data gets corrupted at receiver side.
File size is appropriately received at receiver side then also file gets corrupted
Please help me
My Code
<?php
ini_set('memory_limit','256M');
include "phpmailer/class.smtp.php";
include "phpmailer/class.phpmailer.php";
$Host = "mail.gmail.com"; // SMTP servers
$Username = "*******#gmail.com"; // SMTP password
$Password = "******"; // SMTP username
$From = "*****#gmail.com";
$FromName = "from";
$str =$_SESSION['MailAll'];
$arr=explode(",",$str);
print_r ($arr);
$Tos=$arr;
// $Tos=json_encode($Tos);
$Ccs = array(
"CC Name 1" => "cc-email-1#yahoo.com",
"CC Name 2" => "cc-email-2#gmail.com"
);
$Subject ="Project Abstract";
$Body =$_POST['mailcont'] ;;
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = $Host;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = $Username;
$mail->Password = $Password;
$mail->From = $From;
$mail->FromName = $FromName;
foreach($Tos as $key => $val){
$mail->AddAddress($val , $key);
}
//foreach($Ccs as $key => $val){
//$mail->AddCC($val , $key);
//}
$mail->WordWrap = 50; // set word wrap
$mail->Priority = 1;
$mail->IsHTML(true);
/////attachment
$str=trim($_SESSION['DOCFILE']);//eg-"Time Table Generator.docx","one_size_does_not_fir_all.pdf"
$arr=explode(",",$str);
for($i=0;$i<count($arr)-1;$i++){
$mail->AddAttachment($arr[$i]);
echo 'array size '.$arr[$i];
}
$mail->Subject = $Subject;
$mail->Body = $Body;
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
// header('location:../sendABS.php');
echo 'Message has been sent.';
}
?>

Categories