Sending email with PHPMailer and creating PDF - php

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

Related

Attach PHP fputcsv as PHPMailer attachment

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

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

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.

Unable to send email using core php

I'am newbie in php. I'am trying to send email using php but I don't know what's wrong in my code. I googled a lot but nothing has worked yet. Here is my php code. I'am using class.phpmailer.php.
<?php
require("phpmailer-master/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "myemail#googlemail.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
$webmaster_email = "recipient#googlemail.com"; //Reply to this email ID
$email="username#domain.com"; // Recipients email ID
$name="myname"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"Webmaster");
$mail->WordWrap = 50; // set word wrap
$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
I could finally send a mail using php. Here is the code:
<?php
require_once('class.phpmailer.php');
include("class.smtp.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = 'sender#mail.com';
$mail->Password = 'sender_password';
$mail->SMTPAuth = true;
$mail->From = 'sender#mail.com';
$mail->FromName = 'sender';
$mail->AddAddress("sender#mail.com");
$mail->AddReplyTo("sender#mail.com", 'Information');
$mail->IsHTML(true);
$mail->Subject = "Sample exmple to check proper working of mail function";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->Body = "Hello ";
$path = $_POST['upload'];
$mail->AddAttachment($path); // attachment
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message sent!";
}
?>
<?php
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
// Comment out this line here it is wrong
// IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "username#gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$webmaster_email = "username#doamin.com"; //Reply to this email ID
$email = "username#domain.com"; // Recipients email ID
$name = "name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email, $name);
$mail->AddReplyTo($webmaster_email, "Webmaster");
$mail->WordWrap = 50; // set word wrap
// i would also comment out these lines, get it working without attachments first
// then add then back in after (if you want attachments)
// $mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
// $mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if (!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
// at the end of the pasted code above, you have these lines (below here) doubled up.
// remove them
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>

Attachment not sent with Email

I am developing a small E-mail app using PHP, For sending out emails I use PHPMailer, All the functionalities work apart form one "Attachments". Attachments just don't go through with the sent email. I tried many different ways to fix it but the one I have now I belief is not far off a working order....
I will post small parts of code that deal with the Attachment process....
HTML Code:
<form action="php/smtp_saved.php" method="post">
<input type="file" name="attach" id="attach" />
</form>
PHP Code:
if ($_POST['action'] == 'Send') {
if (preg_match('<,>', $email['recipient'])) {
$address = explode(',', $email['recipient']);
if (sizeof($address) < 19) {
foreach ($address as $recipient) {
$save = new saveSaved();
$save->save($_SESSION['user'], $email['recipient'], gmdate('Y-m-d H:i:s', strtotime ('+1 hour')), $_SESSION['delete'],$email['HTML']);
require_once('../PHPMailer/PHPMailerAutoload.php');
require_once('../PHPMailer/class.smtp.php');
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->Port = '465';
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $_SESSION['user']; // SMTP username
$mail->Password = $_SESSION['pass']; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->From = $_SESSION['user'];
$mail->FromName = 'OneTwoTrade';
//$mail->addAddress($email['recipient']); // Add a recipient
//$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addAddress(trim($recipient));
if (preg_match('<,>', $email['cc'])) {
$cc = explode(',', $email['cc']);
if (sizeof($cc) < 9) {
foreach ($cc as $carbonC) {
$mail->addCC($carbonC);
}
} else {
exit ('Max 10 Recipients Per Email');
}
} else {
$mail->addCC($email['cc']);
}
//$mail->addBCC('bcc#example.com');
$mail->WordWrap = 50; // Set word wrap to 50 characters
if(is_uploaded_file($_FILES['attach']['tmp_name'])) {
$file = $_FILES['attach']['name'];
$mail->AddAttachment($file);
}
/*
if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK){
$mail->addAttachment($_FILES['uploaded_file']['tmp_name'],
$_FILES['uploaded_file']['name']);
}
*/
// Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $email['subject'];
$mail->Body = $email['HTML'];
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
//$mail->SMTPDebug =1;
if (!$mail->send()) {
header("Location: ../saved_emails.php?error2");
//echo 'Message could not be sent.';
//echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
}
}
}
Can someone help me to spot a mistake or direct to a decent source of information....?
When attaching a file via a form add enctype="multipart/form-data" attribute to the form tag. I think the problem occurs because of this.
<form action="php/smtp_saved.php" method="post" enctype="multipart/form-data">
<input type="file" name="attach" id="attach" />
</form>
After a little search, I have found this: Both temp_name and name keys for the attached file are used in AddAttachment() function:
if(isset($_FILES['attach']) && $_FILES['attach']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['attach']['tmp_name'], $_FILES['attach']['name']);
}
$file = $_FILES['attach']['name']; should be $file = $_FILES['attach']['tmp_name'];. The actual file data is in $_FILES['attach']['tmp_name']. $_FILES['attach']['name'] is just the name given to the uploaded file on the client side.
OK guys Want to thx all of you who tried to help me and pushed me to the solution, I managed to fix it this is what I had to do...
if(is_uploaded_file($_FILES['attach']['tmp_name'])) {
$file = $_FILES['attach']['tmp_name'];
$name = $_FILES['attach']['name'];
$mail->AddAttachment($file, $name);
}
:)))))))))))))))))))))))))))))))))))))))))
Works like a charm, just checked the PHPMailer Documentation and the AddAttachment Method needs two parameters,

Categories