Swift mailer attachment - php

I have tried email extensions in yii twice.
1.YII-MAIL
2.PHP MAILER
Now i would like to try out swift mailer.I have downloaded the package from here http://swiftmailer.org/download and added it to the extensions folder in YII.
Here i have a form ,with fields for name,email,phone and an attachment.
I am saving the file uploaded to a folder called resumes under images folder ,at the same time i am sending a mail with all details along with the uploaded file as an attachment .But on clicking create button i am getting this error
include(Swift_Message.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory
Here is the controller action i have tried so far
public function actionCreate()
{
$this->layout='static_inner';
$model=new LriCareer;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['LriCareer']))
{
$rnd = rand(0,9999);
$model->attributes=$_POST['LriCareer'];
if($uploadedFile=CUploadedFile::getInstance($model,'career_resume'))
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->career_resume = $fileName;
if($model->save())
{
$uploadedFile->saveAs(dirname(Yii::app()->basePath) . '/images/resumes/'.$fileName);
$message = new YiiMailMessage;
$first_name="hello";
$message->setBody($first_name);
$message->subject = 'My Subject';
$message->addTo('fazeela.ma#longriverinfotech.com');
$message->from = Yii::app()->params['adminEmail'];
$uploadedFile = CUploadedFile::getInstanceByName('fileupload'); // get the CUploadedFile
$uploadedFileName = $uploadedFile->tempName; // will be something like 'myfile.jpg'
$swiftAttachment = Swift_Attachment::fromPath($uploadedFileName);
$message->attach($swiftAttachment);
}
}
else
{
if($model->save())
$this->redirect(array('view','id'=>$model->career_id));
}}
$this->render('create',array(
'model'=>$model,
));
}
I dont see Swift_message.php in the folder.Can any one out there can look into the problem

There is a Swiftmailer Extension for Yii Framework. I've personally used in a couple of projects and its awesome.
How to attach Files:
$message = new YiiMailMessage;
$message->setBody($first_name);
$message->subject = 'My Subject';
$message->addTo('my#domain.com');
$message->from = Yii::app()->params['adminEmail'];
$uploadedFileName = CUploadedFile::getInstance($model,'career_resume');
$uploadedFileName = $uploadedFile->tempName; // will be something like 'myfile.jpg'
$swiftAttachment = Swift_Attachment::fromPath($uploadedFileName);
$message->attach($swiftAttachment);

Related

How to send fillable pdf (filled with pdftk) via PHPMailer?

I have a form on a website that customers fill. When user filles the form and clicks submit data is sent to a pdf(invoice) I've already created and certain spots in pdf are filled with that data. I did this using PDFTK library:
public function generate($data)
{
$filename = date("d-m-Y-His") . ".pdf";
$pdf = new Pdf('./form.pdf');
$pdf->fillForm($data)
->flatten()
->saveAs('./completed/' . $filename);
$path = './completed/' .$filename;
return $path;
}
The problem is, i dont know how to send this filled pdf via PHPMailer library, as pdf is recquired to be a string in order to work with phpmailer.
$pdf = new GeneratePDF;
$response = $pdf->generate($data);
$email = new PHPMailer();
$email->SetFrom('you#example.com', 'Your Name');
$email->Subject = 'Test';
$email->Body = 'Test';
$email->AddAddress( 'mail exmp' );
$email->AddAttachment( $response , 'NameOfFile.pdf' );
$email->Send();
And how to actually save file in cpanel server, as when i do this it doesnt work on a server.
pdf is recquired to be a string in order to work with phpmailer
This is not true. addAttachment() requires that you pass in a path to a local file on disk, so you could do:
$email->addAttachment(generate(), 'NameOfFile.pdf');
You can pass in a binary string using addStringAttachment(), but that's not what you're asking for here.

How to convert UploadedFile object to Swift_Mime_MimeEntity

I have a Symfony 3.3 contact form that sends an email. Now I am trying to add an attachment to the form. I insert the following line in my sendEmail function:
->attach($data["attachment"])
... and I get the following error:
Argument 1 passed to Swift_Mime_SimpleMessage::attach() must implement
interface Swift_Mime_MimeEntity, instance of
Symfony\Component\HttpFoundation\File\UploadedFile given
So my question is: How do I convert my UploadedFile object into something that SwiftMailer will be happy with?
====
Edit #1: I tried this with no success:
$fullFilePath = $data["attachment"]->getPath() . '/' . $data["attachment"]->getClientOriginalName();
$attachment = \Swift_Attachment::fromPath($fullFilePath);
Attaching that "attachment" just resulted in the email not being sent, though the application acted as if it had sent the form.
====
Edit #2: Progress! I'm now able to get a useful error. This code ...
$extension = $data["attachment"]->guessExtension();
if($extension !== 'rtf'){
die('Please give us an rtf file. TODO: Put a better message here!');
}
$newFilePath = '/tmp';
$newFileName = 'temporary.rtf';
$data["attachment"]->move($newFilePath, $newFileName);
... gives me an error like this:
Could not move the file "/tmp/phpnIqXDr" to "/tmp/temporary.rtf" ()
... which is very frustrating, since I know that /tmp is writeable by every user.
You don't need to move the file, Symfony\Component\HttpFoundation\File\UploadedFile class returns the path and has methods to get the filename and mimetype.
This code works for me:
$message->attach(
\Swift_Attachment::fromPath($data["attachment"])
->setFilename(
$data["attachment"]->getClientOriginalName()
)
->setContentType(
$data["attachment"]->getClientMimeType()
)
);
Credit to toolpixx
Here is the code that ended up working for me:
private function sendEmail($data)
{
$vgmsContactMail = self::contactMail;
$mailer = $this->get('mailer');
/* #var $uploadedFile UploadedFile */
$uploadedFile = $data["attachment"];
$extension = $uploadedFile->guessExtension();
if(!in_array($extension, ['pdf','rtf']) ){
die('Please upload a .pdf or .rtf file.');
}
$newFilePath = '/tmp';
$newFileName = 'temporary' . rand(0,10000) . '.rtf';
$uploadedFile->move($newFilePath, $newFileName);
$attachment = \Swift_Attachment::fromPath('/tmp/' . $newFileName);
$message = \Swift_Message::newInstance("VGMS Contact Form: ". $data["subject"])
->setFrom(array($vgmsContactMail => "Message by ".$data["name"]))
->setTo(array(
$vgmsContactMail => $vgmsContactMail
))
->setBody($data["message"]."<br>ContactMail :".$data["email"])
->attach($attachment)
;
return $mailer->send($message);
}

Allowed extension phpmailer

how could i change my code to only accept some extensions.
look my code :
<?php
ob_start();
$_SESSION['nomecomp'] = $_POST['nomecomp'];
$email_env = $_POST['email_env'];
if (isset($email_env)) {
//variaveis vindas da pagina
$varcritico = $_POST['varcritico'];
$nomecomp = $_POST['nomecomp'];
$chapa = $_POST['chapa'];
$funcao = $_POST['funcao'];
$setor = $_POST['setor'];
$unidade = $_POST['unidade'];
$deschelp = $_POST['deschelp'];
//variveis do modal
//$email_env = $_POST['email_env'];
//$senha_env = $_POST['senha_env'];
<td>$deschelp</td>
</tr>
</table>'";
/**
* PHPMailer multiple files upload and send example
*/
$msg = '';
//if (array_key_exists('userfile', $_FILES)) {
// Create a message
// This should be somewhere in your include_path
include ("lib/PHPMailerAutoload.php");
$mail = new PHPMailer();
i have tried add some codes , but dont made sucess , for example , could i try push the array and see if the extension are inside some array ?
thanks.
Presuming you want to check the uploaded file types before moving them:
$AllowedFileTypes = array("pdf","txt"); // build array
$FileName = $_FILES['userfile']['name']; // get filename of file input
$FileType = end((explode(".", $FileName))); // get file type/extension
if(in_array($FileType, $AllowedFileTypes)){ // check to see if file type is allowed
// perform copy/move file
}
else{
// ignore/alert/whatever
}
Note: You may have to amend the variables to suit your requirements.
If you wish to validate the file type/extension before submitting the form, take a look at jQuery validation for file input: https://stackoverflow.com/a/20929391/715105

Email attachments from outside sources not working

I've recently created a page on our site where users can upload an image and email it to an email address set up specifically to keep the uploaded documents.
I've tested this myself and it works, with the attachments arriving in gmail as expected.
However, whenever someone from outside uses this feature the attachment in the email is unavailable, or not could not be loaded, when we try to open it.
The code is split between 2 files, a controller and a helper. Here's the code (For the sake of saving some space I've removed all error checks, but in the actual code they are all still in place and not picking up any errors whatsoever):
controller
$helper = [GET HELPER];
/** Upload the file to a temp location so that we can attach it to an email */
$uploader = new Varien_File_Uploader('filename');
$uploader->setAllowedExtensions(array(
'image/jpeg',
'image/jpg',
'image/png',
'application/pdf'
))
->setAllowRenameFiles(true)
->setFilesDispersion(false);
$path = $helper->getFileStorageLocation(); // Will store files in /tmp
if (!is_dir($path))
{
mkdir($path, 0775, true);
}
$uploader->save($path, $_FILES['filename']['name']);
$result = $helper->sendMail($_FILES['filename']['name']);
if ($result)
{
$uploadSuccess = true;
/** Remove the temp file */
unlink($path . DS . $_FILES['filename']['name']);
}
helper
/** Declare variables */
$order = Mage::getModel('sales/order')->load($orderId);
$file_incremented_id = $order->getIncrementId();
$copyTo = $this->getCopyTo();
$copyFrom = $this->getCopyFrom();
$subject = 'proof of upload for ' . $file_incremented_id;
$copyTo = explode(',', $copyTo);
$body = '<span>Please see attachment</span>';
$file = $this->getFileStorageLocation() . DS . $filename; // function receives filename from whatever is calling it
$attachment = file_get_contents($file);
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!$copyTo)
{
return false;
}
$mail = Mage::getModel('core/email_template');
$mail->setSenderName('Uploader');
$mail->setSenderEmail($copyFrom);
$mail->setTemplateSubject($subject);
$mail->setTemplateText($body);
$mail->getMail()->createAttachment(
$attachement,
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
$file_incremented_id . '.' . $extension // Set order number as file name
);
try
{
$mail->send($copyTo);
return true;
}
catch (Exception $e)
{
return false;
}
Can anyone see anything that might be causing the issue, or think of what it might be based on my explanation of the setup?
So the problem, in the end, was filesize. My fault for not posting the $_FILES variable.
I saw it a bit later and the variable had error = 1, meaning that the file's size was larger than what was allowed by the max_upload_filesize in the php.ini

Why is PHPmailer not sending the attachment?

Ive been working on create a file upload form using PHPmailer to send as attachments.
Ive finally got it to send the email, but its not sending the attachment. Here's my HTML form:
<input type="file" class="fileupload" name="images[]" size="80" />
And here's my php processor code:
<?php
require("css/class.phpmailer.php");
//Variables Declaration
$name = "the Submitter";
$email_subject = "Images Attachment";
$Email_msg ="A visitor submitted the following :\n";
$Email_to = "jonahkatz#yahoo.com"; // the one that recieves the email
$email_from = "someone#someone.net";
$attachments = array();
//
//
//------Check TYPE------\\
uploadFile();
//
//==============upload File Function============\\
//
function uploadFile() {
global $attachments;
foreach($_FILES['images']['name'] as $key => $value)
{
//
if(!empty($value))
{
$filename = $value;
//the Array will be used later to attach the files and then remove them from ser
ver ! array_push($attachments, $filename);
$dir = "uploads/$filename";
$success = copy($_FILES['images']['tmp_name'][$key], $dir);
}
//
}
$dir ="uploads/$filename";
if ($success) {
echo " Files Uploaded Successfully<BR>";
SendIt();
//
}else {
exit("Sorry the server was unable to upload the files...");
}
//
}
//
//==== PHP Mailer With Attachment Func ====\\
//
function SendIt() {
//
global $attachments,$name,$Email_to,$Email_msg,$email_subject,$email_from;
//
$mail = new PHPMailer();
$mail->IsQmail();// send via SMTP
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
//now Attach all files submitted
foreach($attachments as $key => $value) { //loop the Attachments to be added ...
$mail->AddAttachment("uploads"."/".$value);
}
$mail->Body = $Email_msg."Name : ".$name"\n";
//
$mail->IsHTML(false);// send as HTML
$mail->Subject = $email_subject;
if(!$mail->Send())
{
echo "Message was not sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
//
echo "Message has been sent";
// after mail is sent with attachments , delete the images on server ...
foreach($attachments as $key => $value) {//remove the uploaded files ..
unlink("uploads"."/".$value);
}
//
}
//
?>
Ive checked, and the file IS being saved in the directory "uploads". Here are the errors im receiving:
Files Uploaded Successfully
Message was not sent
Notice: Undefined property: phpmailer::$ErrorInfo in /usr/home/jak2234/public_html/new_form/phpmailerprocess.php on line 69
Mailer Error:
If anyone can spot the errors or provide some input how to this that would be so helpful! Thanks in advanced!
Jonah
Ive replaced
foreach($attachments as $key => $value) { //loop the Attachments to be added ...
$mail->AddAttachment("uploads"."/".$value);
With
foreach(array_keys($_FILES['files']['name']) as $key) {
$source = $_FILES['files']['tmp_name'][$key]; // location of PHP's temporary file for this.
$filename = $_FILES['files']['name'][$key]; // original filename from the client
$mail->AddAttachment($source, $filename);
}
And now here are my new errors:
Notice: Undefined index: files in /usr/home/jak2234/public_html/new_form/phpmailerprocess.php on line 58
Warning: array_keys() expects parameter 1 to be array, null given in /usr/home/jak2234/public_html/new_form/phpmailerprocess.php on line 58
Warning: Invalid argument supplied for foreach() in /usr/home/jak2234/public_html/new_form/phpmailerprocess.php on line 58
Strict Standards: Creating default object from empty value in /usr/home/jak2234/public_html/new_form/phpmailerprocess.php on line 68
Fatal error: Call to undefined method stdClass::IsHTML() in /usr/home/jak2234/public_html/new_form/phpmailerprocess.php on line 70
As I said in your other question, the first warning is due to you using $filename in line 10 of your script, without having assigned a value to it first:
$dir ="uploads/$filename"; // $filename has NOT been defined at this point.
As well, for your attachments, why not simply do:
foreach(array_keys($_FILES['files']['name']) as $key) {
$source = $_FILES['files']['tmp_name'][$key]; // location of PHP's temporary file for this.
$filename = $_FILES['files']['name'][$key]; // original filename from the client
$mail->AddAttachment($source, $filename);
}
There's no need to do all the file copying, building your own paths, etc... Just directly attach the temporary file PHP creates for you, and name it with whatever the original filename was.
Your script is far more complicated than it needs to be.

Categories