It just so happens we have two files that are the exact same size that we some times try to send together. We can send anything else we want with these files but as soon as we include both of them it only sends the first one. I'll include my phpmailer code just to be safe but its worked thus far.
$mail = new PHPMailer(true);
$mail->IsSendMail();
$mail->SetFrom($from_addy, $from_name);
foreach(explode(',',$to) as $address1){
foreach(explode(';',$address1) as $address2){
if($address2 != ''){
$mail->AddAddress($address2);
}
}
}
$mail->WordWrap = 70;
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $css.$message;
$mail->AltBody = nl2br($message);
$mail->MsgHTML($css.$message);
if(is_array($attachments)){
foreach($attachments as $attachment){
$file = file_get_contents($attachment['tmp_name']);
$mail->AddStringAttachment($file,$attachment['name']);
// I have put checks here and both attachments do make it this far.
}
}
You're not checking the return value from addStringAttachment so you don't know if it's working or not. PHPMailer doesn't throw exceptions for everything, and while you've requested them, you're not catching them anyway. Why read the file and use addStringAttachment - why not read the attachment directly from the file with addAttachment? String attachments are more useful when you need to attach the results of a remote API call, PDF generation etc. Like this:
if (!$mail->addAttachment($attachment['tmp_name'], $attachment['name'])) {
echo "Failed to attach ".$attachment['tmp_name'];
}
Why are you using isSendmail()? It's unlikely you need that.
You've not presented any evidence that it's got anything to do with the file size - it's not as if attachments are indexed by their size value or anything.
You're setting AltBody before calling msgHTML(), which overwrites AltBody. Calling nl2br() on AltBody contents is pointless because AltBody will usually be presented as plain text, so <br> tags will show up.
It looks like your $attachment array may be sourced from $_FILES, in which case it looks you are handling file uploads unsafely. read the PHP docs on that, and look at the "send file upload" example provided with PHPMailer.
Overall, it looks like you've based your code on a very old PHPMailer example, so make sure you're using the latest version, and look at the examples provided with it.
Related
I tried to attach my local file using PHP Mailer. I'm getting attachment only if the attachment file is in own server, but when I tried to attach the file from my c drive say [C:\Users\emp10144\Downloads], am getting attachment but with blank page. Did I need to modify my codings. Below is the codings I have used.
$mail->From = 'admin123#sampledemos123.online';
$mail->FromName = 'Admin';
$mail->AddAddress('targetmail#gmail.com', 'User'); // Add a recipient
//$mail->AddAddress('ellen#example.com'); // Name is optional
//$mail->AddAttachment('Daily_Milk_Report.csv','Daily_Milk_Report.csv');
This is working fine as the attcahment file is in own server
$filename = "C:\Users\emp10144\Downloads','Daily_Milk_Report.csv"; // Need to attcah this file from C drive/folder.
//$string = file_get_contents("C:\Users\emp10144\Downloads\sample.pdf");
$mail->AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/vnd.ms-excel');
$mail->IsHTML(true); // Set email format to HTML
No, you cannot pass a URL to addAttachment and have it fetch the resource.
This is intentional; PHPMailer is not an HTTP client, and actively avoids being one. If you want to do this, you need to take responsibility for the fetch yourself, which is most easily achieved like this:
$mail->addStringAttachment(file_get_contents($url, 'myfile.png'));
I'm having really a hard time with TCPDF, in what I am seeing from my searching here in Stack Overflow, I can't find any help in understanding on how to use TCPDF. I can't figure out on how to include tcpdf in my website unlike FPDF, I'll just have to copy paste required folders and files inside the folder of the website then place a require(fpdf.php); in the pages. How do I do that in TCPDF?
I can't even figure out how to connect to my database unlike FPDF.
I want to know the basics in understanding TCPDF.
Can someone guide me in understanding TCPDF?
I have used this DOMPDF tutorial to convert my HTML file into PDF. You can send this PDF file to user mail also. It is very easy to understand. Try this and please let me know whether it help you or not. You can see demo here
EDIT :- If you don't want to send a mail then just remove the following code from form.php
// Load the SwiftMailer files
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer
$message = Swift_Message::newInstance()
->setSubject('How To Create and Send An HTML Email w/ a PDF Attachment') // Message subject
->setTo(array($post->email => $post->name)) // Array of people to send to
->setFrom(array('no-reply#net.tutsplus.com' => 'Nettuts+')) // From:
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
->attach(Swift_Attachment::newInstance($pdf_content, 'nettuts.pdf', 'application/pdf')); // Attach the generated PDF from earlier
// Send the email, and show user message
if ($mailer->send($message))
$success = true;
else
$error = true;
I want to do this:
$mail = new PHPMailer;
$mail->AddAttachment('text in file', 'file.txt');
so the attachment can have dynamic content. I can only use real file as attachment now. Obviously, real file is static, I want to generate some content dynamically and attach it to the mail. There must be some way to do it, I guess it's not that obscure feature. Someone knows how?
$mail->AddStringAttachment($string,$filename,$encoding,$type);
http://phpmailer.worxware.com/?pg=tutorial#3
As always here is the place where I have learned a lot. And I have now a new things to learn:
I have a html form:
<tr><td width="16%">File attachment</td><td width="2%">:</td><td><input type="file" name="fileatt" /></td></tr>
and a mail.php:
$attachfile=$_POST["fileatt"];
and a correct swiftmailer code to send emails out;
I have googled and I found many examples how to send attachment with a file stored on the website but I would like to do it on the fly. So when you submit the button it would send it to peoples out rather than uploading the file.
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('mail.server.co.uk', 25)
->setUsername('user')
->setPassword('pass')
;
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance($subject)
->setFrom(array('emai#emai.com' => 'name'))
->setBody($html, 'text/html')
;
// Add alternative parts with addPart()
$message->addPart(strip_tags($html), 'text/plain');
// Send the message
$result = $mailer->send($message);
could anyone help me how to do the on the fly file uploading, please? Thanks in advance!!!
There's a simple way to do this, here you go:
$message->attach(
Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('myfilename.jpg')
);
That's one way SwiftMail can do this, now just the /tmp file, and turn the above into the following:
Assuming: fileatt is the variable for the $_FILE, ['tmp_name'] actually is the tmp file that PHP creates from the form upload.
$message->attach(
Swift_Attachment::fromPath($_FILES['fileatt']['tmp_name'])->setFilename($_FILES['fileatt']['name'])
);
More information on SwiftMail Attachments can be found on this docs page
More information on $_FILES can be found here on w3schools, despite I don't like w3schools, this page is solid.
Another way to do this, using only a single variable for path and filename is:
$message->attach(Swift_Attachment::fromPath('full-path-with-attachment-name'));
Single Attachment
My answer is similar to that of André Catita. However, in Laravel 6 you can use $request instead of $_FILES. Let me simplify the code above:
$path = $request->file('import')->getPathName();
$fileName = $request->file('import')->getClientOriginalName();
$message->attach(
Swift_Attachment::fromPath($path)->setFilename($fileName)
);
Here I assume that the name of your file tag is import. For eg: <input type="file" name="import" />
Multiple Attachments
Now, lets say instead of single attachment you need multiple attachments. Then the code needs to be changed.
First your html code will become: <input type="file" name="import[]" multiple />
And for backend or laravel; code will be:
$files = $request->file('import');
foreach($files as $file){
$path = $file->getPathName();
$fileName = $file->getClientOriginalName();
$message->attach(
Swift_Attachment::fromPath($path)->setFilename($fileName)
);
}
What is the easiest way to attach a PDF to an email via DOMPDF?
The end of my script I am using (part of it) is below:
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
//below to save the pdf file - not needed if emailing pdf
file_put_contents('/home/ststrave/public_html/pdf/STS_Brochure.pdf', $dompdf->output());
//below to open pdf in browser - required
$dompdf->stream("STS_Brochure_".rand(10,1000).".pdf", array("Attachment" => false));
jexit();
Just for clarification - this is being used in Joomla.
Appreciate the simplest/quickest way using standard PHP mail function.
Cheers ;-)
Ok. You already accepted an answer, but for anyone else coming here, I think there is an easier way, but it's also not PHP's standard mail function, which really isn't going to work. If you can get the pear packages Mail and Mail_mime, it's really easy to send emails with attachments. You can also directly attach the DomPDF output without creating a file, like so:
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->set_paper("letter", "portrait" );
$dompdf->render();
$output = $dompdf->output();
$mm = new Mail_mime("\n");
$mm->setTxtBody($body);
$mm->addAttachment($output,'application/pdf','output.pdf', false);
$body = $mm->get();
$headers = $mm->headers(array('From'=>$from,'Subject'=>$subject));
$mail =& Mail::factory('mail');
if($mail->send($to,$headers,$body)){
echo "Your message has been sent.";
}
Here is the solution I was looking for when I came here:
Instead of:
$dompdf->stream();
do this:
$fileatt = $dompdf->output();
And than send mail using PHPMailer and attach the pdf to mail like so:
$filename = 'MyDocument.pdf';
$encoding = 'base64';
$type = 'application/pdf';
$mail->AddStringAttachment($fileatt,$filename,$encoding,$type);
In this way you don't have to deal with saving the file on the server.
PHP's mail function has no "standard" file attachment method. It's an extremely barebones interface to the SMTP system that forces you to do ALL the work of attaching a file yourself.
I strongly suggest using PHPMailer or Swiftmailer to do the email for you - it reduces the heavy grunt work of generating your own MIME email and inserting the attachment (many many lines of code) does to maybe 5 lines total.
Note that neither of them will handle a streamed PDF from DOMPDF. You'll have to save the PDF to a temporary file and attach that,
Raw Data Attachments
The attachData method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The attachData method accepts the raw data bytes as its first argument, the name of the file as its second argument, and an array of options as its third argument:
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders.shipped')
->attachData($this->pdf, 'name.pdf', [
'mime' => 'application/pdf',
]);
}