Attach PHP fputcsv as PHPMailer attachment - php

The first part of my function generates a CSV file using PHP's fputcsv, I want to then email that CSV using PHPMailer which I also have installed.
Generate CSV file from array.
$output = fopen("php://output",'w') or die("Can't open php://output");
// Add column headings.
fputcsv($output, array('SKU', 'ASIN', 'Current Rating', 'Previous Week', 'Difference', 'Category', 'Total Ratings'));
foreach( $ratings as $rating ) {
fputcsv( $output, $rating );
}
fclose($output) or die("Can't close php://output");
Send email via PHPMailer
// Create a new PHPMailer instance
$mail = new \PHPMailer\PHPMailer\PHPMailer();
// Tell PHPMailer to use SMTP
$mail->isSMTP();
// Set the hostname of the mail server
$mail->Host = 'smtp.eu.mailgun.org';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
// Set who the message is to be sent from
$mail->setFrom('', '');
$mail->Subject = 'Weekly ASIN Ratings Report';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
// Attach an image file
$mail->addAttachment('');
// Send the message, send errors to Sentry.
if (!$mail->send()) {
\Sentry\captureMessage( $mail->ErrorInfo );
} else {
echo 'Message sent!';
}
What I tried
$mail->addAttachment($output);
I got the email but no attachment at all.

You can use it like -
$mail->AddAttachment( $filePath , 'filename.csv' );

Related

How to get PHP variable from another file?

I'm trying to make a forgot password system with PHPMailer on xampp.
But when I send an email,the email body is a html mail template,what I get from another file $mail->Body = file_get_contents('mail_template.php');,and I have problem,because I don't know how should I get the data of the $url variable and send it to mail_template.php file to use it for the link in the mail.
I tried the include 'filename.php'; command,but haven't worked.
Here is the code:
if (isset($_POST["submitButton"])) {
$emailTo = $_POST["email"];
$code = md5(uniqid(rand(), true));
$query = $con->prepare("INSERT INTO resetpasswords(code,email) VALUES('$code', '$emailTo')");
$query->execute();
if (!$query) {
exit("Something went wrong...");
}
$mail = new PHPMailer(true);
try {
//Server settings // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail#gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 465; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('mail#mail.com', 'Email');
$mail->addAddress($emailTo); // Add a recipient
$mail->addReplyTo('no-reply#website.com', 'No reply');
// Content
$url = "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/resetPassword/code/$code";
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Reset your password!';
$mail->Body = file_get_contents('mail_template.php');
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
} catch (Exception $e) {
echo "Message could not be sent. Error: {$mail->ErrorInfo}";
}
header("refresh:10;url=login.php");
}
So from this php file,I want to send the data of the $url to the mail_template.php
Is this possible to do?
To send data to another url in php you have to try the following url:
`mail_template.php?data=mail#gmail.com`
then inside an empty mail_template.php do -
<?php
if (isset($_GET['data'])) {
$test = $_GET['data'];
//print the data added to the url
echo $test;
}
?>

PhpMailer Multiple Attachments

I´m trying to send multiple attachments with phpmailer. I get the whole url of the files I'm trying to send and with a for loop I put it into the $mail->addAttachment parameter, but when i try to send it throws the error:
Could not access file:....
// ADJUNTOS
$urls_x = explode(',',$urls);
// QUITA EL ULTIMO ELEMENTO DE LA LISTA QUE VIENE VACIO
$unset = count($urls_x);
unset($urls_x[$unset-1]);
$urls_count = count($urls_x);
$nombre = $paciente['nombre1'].' '.$paciente['nombre2'].'
'.$paciente['apellido1'].' '.$paciente['apellido2'];
$correo = strtolower($paciente['email']);
$mail = new PHPMailer(TRUE);
try {
$mail->CharSet="utf-8";
$mail->setFrom('sender_x#xxxx.com.co', 'SENDER');
$mail->addAddress($correo, $nombre);
$mail->Subject = 'XXXX SUBJECT';
$mail->IsHTML(true);
$mail->AddEmbeddedImage('../../img/mail/body.png', 'bodyimg',
'../../img/mail/body.png');
$mail->Body = "<img src=\"cid:bodyimg\" />";
for($i=0;$i<$urls_count;$i++){
$mail->addAttachment($urls_x[$i]);
}
}
Thanks a lot for your cooperation.
You're passing in URLs instead of local paths, which is deliberately not supported by addAttachment. PHPMailer is not an HTTP client, so fetch the files yourself, and then pass them to PHPMailer. For example:
file_put_contents('/tmp/file.jpg', file_get_contents($url));
$mail->addAttachment('/tmp/file.jpg');
Alternatively, skip writing it to a file and pass it as a string (make sure you pass in a filename or set the MIME type - see PHPMailer docs on that):
$data = file_get_contents($url);
$mail->addStringAttachment($data, 'file.jpg');
You might want to do some error checking around these too.
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp1.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'jswan';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->From = 'from#example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('josh#example.net', 'Josh Adams'); // Add a recipient
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$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;
exit;
}
echo 'Message has been sent';
try this, its working for me. you can add multiple add attachment to send attachments

Sending email with PHPMailer and creating PDF

I have a script that runs FPDF that creates and stores a PDF file in a folder.
That works fine.
My question is, am I able to send an email in that same script?
I have attempted it but i always get "Page cannot be displayed"
EDIT I dont want the files attached to the email. I just wish to send a email with some wording thats all.
Wont paste my whole code as its just the end that has the problem:
//display pdf
mkdir("FileBrowser/files/$name", 0777);
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "FileBrowser/files/$name/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
$filename = "FileBrowser/files/$name/$name.pdf";
$pdf->Output($filename, 'F');
require ('PHPMailer/class.phpmailer.php');
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = '****'; // Specify main and backup server
$mail->Port = 587; // Set the SMTP port
$mail->SMTPAuth = true;
$mail->Username = '****'; // SMTP username
$mail->Password = '****'; // SMTP password
$mail->From = 'Testing#test.co.za';
$mail->FromName = 'Testing';
$mail->AddAddress('****', 'John Smith'); // Add a recipient
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <strong>in bold!</strong>';
$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;
exit;
}
?>

How do I send a FPDF doc using PHPMailer

I would like to merge or link the FPDF and PHPMailer code so that a document is generated and sent by email. I do not want to save the file. I am unable to find a solution. Below is the working code for FPDF and also for PHPMailer. Unable to merge the two together.
FPDF website says to do this
$mail = new PHPMailer();
...
$doc = $pdf->Output('', 'S');
$mail->AddStringAttachment($doc, 'doc.pdf', 'base64', 'application/pdf');
$mail->Send();
FPDF code:
require_once('fpdf/fpdf.php');
$fpdf = new FPDF();
$text="test";
$fpdf->SetMargins(0, 0, 0);
$fpdf->SetAutoPageBreak(true, 0);
define('FPDF_FONTPATH', 'font/');
$fpdf->AddFont('Verdana', '','verdana.php'); // Standard Arial
$fpdf->addPage('L');
$fpdf->Image('images/certificate.jpg', 0, 0, 297, 210);
$fpdf->SetFont('Verdana', '');
$fpdf->SetFontSize(28);
$fpdf->SetTextColor(32, 56, 100);
$fpdf->SetXY(108, 52); //
$fpdf->Cell(80, 6, $text, 0,0, 'C');
$fpdf->Output('Filename.pdf', 'i');
PHPMailer code:
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'gator3095'; // Specify main and backup server
$mail->Port = 587; // Set the SMTP port
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'test#hotmail.com.com';
$mail->FromName = 'John Doe';
$mail->AddAddress('recipient#hotmail.com', ''); // Add a recipient
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'subject';
$mail->Body = 'message body';
$mail->AltBody = 'messge body';
$mail->AddAttachment("c:/temp/test.php", "test.php");
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Replace $fpdf->Output('Filename.pdf', 'i'); by $fpdf->Output('Filename.pdf', 'S'); to save your PDF on the harddrive instead of sending it directly to the browser (as explained in the doc).
Then call your FPDF code to generate the PDF file in the begining or before your PHPmailer.php code, replace $mail->AddAttachment("c:/temp/test.php", "test.php"); by $mail->AddAttachment("[...the exact place where your file is..]/Filename.pdf", "Filename.pdf");
And finally, before your last echo, add unlink('Filename.pdf'); to delete the temporary PDF file you've just sended.

Send attatchment using php mail()

I want to attach a image as an attachment using mail() function.
I am using xampp and want the image to be sent from my computer to an email id.
This code is sending text email easily:
<?php
if(mail('abc#gmail.com','Hello','Testing Testing','From:xyz#gmail.com'))
{
echo "Success";
} else {
echo "Fail";
}
?>
I want to add an image after it using normal mail method of php.
you need to use the pear library for composing or sending the mail.
include_once('Mail.php');
include_once('Mail_Mime/mime.php');
$message = new Mail_mime();
$message->setTXTBody($text);
$message->addAttachment($path_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
here is a way
You could use the Mail class from the Zend library, very simple and no reliance on PEAR.
Its been covered in a previous question here.
I suggest to use Swiftmailer. It is up to date, easy to install and use. You can install it via PEAR, but there are lots of other options you might find more convenient as well.
Example code to send a mail with an attachement taken from the manual:
require_once 'lib/swift_required.php';
// Create the message
$message = Swift_Message::newInstance()
// Give the message a subject
->setSubject('Your subject')
// Set the From address with an associative array
->setFrom(array('john#doe.com' => 'John Doe'))
// Set the To addresses with an associative array
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
// Give it a body
->setBody('Here is the message itself')
// And optionally an alternative body
->addPart('<q>Here is the message itself</q>', 'text/html')
// Optionally add any attachments
->attach(Swift_Attachment::fromPath('my-document.pdf'));
this is using php and ajax it will work 100%
<?php
include "db.php";
if(isset($_POST['tourid']))
{
$to=$_POST['email'];
$file_name = "test/sample.pdf";
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = ''; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = ''; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = ''; //Sets SMTP username
$mail->Password = ''; //Sets SMTP password
$mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = ''; //Sets the From email address for the message
$mail->FromName = ''; //Sets the From name of the message
$mail->AddAddress($to, 'Name'); //Adds a "To" address
$mail->WordWrap = 50; `` //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->AddAttachment($file_name); //Adds an attachment from a path on the filesystem
$mail->Subject = 'Customer Details'; //Sets the Subject of the message
$mail->Body = 'Please Find Tour details in attached PDF File.'; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$message = '<label class="text-success">Tour Details has been send successfully...</label>';
echo $message;
unlink($file_name);
}
}
else
{
echo "sending error";
}
?>

Categories