swiftmailer and email form with attachment - beginner - php

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

Related

PHPMailer 2 files same filesize are not sending both

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.

Add attachements to send mail in Yii

I am fairly new to Yii. I am using YiiMail extension to send mails. I am able to send mails but unable to send attachments with it.
I have got the following code but now knowing what that "tempName" would exactly mean?
mycontroller-
$uploadedFile = CUploadedFile::getInstanceByName('filename'); // get the CUploadedFile
$uploadedFileName = $uploadedFile->tempName; // will be something like 'myfile.jpg'
$swiftAttachment = Swift_Attachment::fromPath($uploadedFile); // create a Swift Attachment
$this->email->attach($swiftAttachment); // now attach the correct type
The if you upload a file (e.g. c:\path\file\myfile.jpg ), if is temporary stored on the server in a temporarry folder with a temporary name (e.g. /tmp/zxhjkqwf.tmp ).
The CUploadedFile wraps all the functions you need to access and manipulate the file.
So the tempname will be the path to your file on the server.
I guess you should try to alter your code lioke this:
$uploadedFile = CUploadedFile::getInstanceByName('filename'); // get the CUploadedFile
$uploadedFileName = $uploadedFile->tempName; // will be something like 'myfile.jpg'
$swiftAttachment = Swift_Attachment::fromPath($uploadedFileName); // create a Swift Attachment from the temporary file
$this->email->attach($swiftAttachment); // now attach the correct type
See more info in the Documentation

Codeigniter access emails with Image as attachments (pop3 imap)

I want to download to get the following information from my emails
sender
sender_email_address
subject
Message
attachments = array(
all attachments
)
any library? suggestions? links?
I have used https://github.com/EllisLab/CodeIgniter/wiki/IMAP and it worked just fine.
Good luck
Here is the library that can be used..
http://garrettstjohn.com/entry/reading-emails-with-php/
plus accessing the library, extracting email and its attachments
http://garrettstjohn.com/entry/extracting-attachments-from-emails-with-php/
Something that was missing in this extraction, was a function to process image, so I had to do it...
function _process_img($attach, $ext){
$directory = "uploads";
$path=realpath(APPPATH."../".$directory);
$file_name="any_name_you_want_to_give".".".$ext;
$file=$directory.$file_name;
if(file_put_contents($path."/".$file_name, $attach)) return $file;
}
Hope it will help someone else too...

PHP - tcpdf and wamp server

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;

PHP: How to send file as the attachment without uploading to sever?

How to send file by mail() function of PHP as the attachment without uploading file to sever (just after submiting the form, using $_FILES array)?
If you're using the $_FILES array, the file is already uploaded to the server (usually in /tmp), so your question doesn't really make sense.
I understand what you mean, though. You want to send it as an attachment without moving it to a more permanent location. This can be done easily using
file_get_contents($_FILES['attachment']['tmp_name']);.
get the file: $attachment = $_FILES['attachment']['tmp_name'];
get the file name: $attachment_name = $_FILES['attachment']['name'];
add the file to mail: $mail->addAttachment($attachment,$attachment_name);

Categories