Is it possible to send an email with an dynamically generated attachment?
I tried it this way:
$this->Email->attachments = array(
'reservation.ics' => array(
'controller' => 'reservations',
'action' => 'ical',
'ext' => 'ics',
$this->data['Reservation']['id']
)
);
But it didn't work.
attachments only takes paths to local files on the server, not URLs. You need to render your attachment to a temporary file, then attach it.
In your controller, this could roughly look like this:
$this->autoRender = false;
$content = $this->render();
file_put_contents(
TMP . 'reservation' . $id . '.ics',
$content
);
$this->Email->attachments = array(
'reservation.ics' => TMP . 'reservation' . $id . '.ics'
);
There are another method to send attachment. firstly store this file on the server then use the server path to send. In the below example I skip the code to store attachment file. There is code for attachment only.
Class EmailController extends AppController {
var $name="Email";
var $components = array ('Email');
var $uses = NULL;
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array(*));
}
function EmailSend(){
$Path = WWW_ROOT."img";
$fileName = 'test.jpg';
$this->Email->from = 'Amit Jha<amit#mail.com>';
$this->Email->to = 'Test<test#test.com>';
$this->Email->subject = 'Test Email Send With Attacment';
$this->Email->attachments = array($Path.$fileName);
$this->Email->template = 'simple_message';
$this->Email->sendAs = 'html';
if($this->Email->send()){
$this->session->setFlash("Email Send Successfully");
$this->redirect('somecontroller/someaction');
}
}
Related
I am trying to send email on codeigniter with attach file.
I always receive email successfully. However , I never receive with attach file. Below is code and highly appreciate for all comments.
$ci = get_instance();
$ci->load->library('email');
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.gmail.com";
$config['smtp_port'] = "465";
$config['smtp_user'] = "test#gmail.com";
$config['smtp_pass'] = "test";
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";
$ci->email->initialize($config);
$ci->email->from('test#test.com', 'Test Email');
$list = array('test2#gmail.com');
$ci->email->to($list);
$this->email->reply_to('my-email#gmail.com', 'Explendid Videos');
$ci->email->subject('This is an email test');
$ci->email->message('It is working. Great!');
$ci->email->attach( '/test/myfile.pdf');
$ci->email->send();
$this->email->attach()
Enables you to send an attachment. Put the file path/name in the first parameter. Note: Use a file path, not a URL. For multiple attachments use the function multiple times. For example:
public function setemail()
{
$email="xyz#gmail.com";
$subject="some text";
$message="some text";
$this->sendEmail($email,$subject,$message);
}
public function sendEmail($email,$subject,$message)
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'abc#gmail.com',
'smtp_pass' => 'passwrd',
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('abc#gmail.com');
$this->email->to($email);
$this->email->subject($subject);
$this->email->message($message);
$this->email->attach('C:\Users\xyz\Desktop\images\abc.png');
if($this->email->send())
{
echo 'Email send.';
}
else
{
show_error($this->email->print_debugger());
}
}
i have this problem before , the problem with the path file , so i change the path file to
$attched_file= $_SERVER["DOCUMENT_ROOT"]."/uploads/".$file_name;
$this->email->attach($attched_file);
And it works fine with me
With Codeigniter 3.1.0 I had same problem. Seems that there is missing a "\r\n":
Content-Type: application/pdf; name="test.pdf"<br>
Content-Disposition: attachment;<br>
Content-Transfer-Encoding: base64<br>
JVBERi0xLjYNJeLjz9MNCjQzNyAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3OTUyMTYvTyA0Mzkv<br>
RSA2ODEwODcvTiA0L1QgNzk0ODA3L0ggWyA1NjQgMjYxXT4+DWVuZG9iag0gICAgICAgICAgICAg<br>
should be:
Content-Type: application/pdf; name="test.pdf"<br>
Content-Disposition: attachment;<br>
Content-Transfer-Encoding: base64<br>
<br>
JVBERi0xLjYNJeLjz9MNCjQzNyAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3OTUyMTYvTyA0Mzkv<br>
RSA2ODEwODcvTiA0L1QgNzk0ODA3L0ggWyA1NjQgMjYxXT4+DWVuZG9iag0gICAgICAgICAgICAg<br>
I changed line 725 in system/libraries/Email from
'content' => chunk_split(base64_encode($file_content)),<br>
to
'content' => "\r\n" . chunk_split(base64_encode($file_content)),<br>
It works for me, but not the perfect fix.
Try putting the full path in $ci->email->attach();
On windows this would like something like
$ci->email->attach('d:/www/website/test/myfile.pdf');
This method has worked well for me in the past.
If you want to send attachment in email Without uploading file on server, please refer below.
HTML View file
echo form_input(array('type'=>'file','name'=>'attach_file','id'=>'attach_file','accept'=>'.pdf,.jpg,.jpeg,.png'));
Controller file
echo '<pre>'; print_r($_FILES); shows below uploaded data.
[attach_file] => Array
(
[name] => my_attachment_file.png
[type] => image/png
[tmp_name] => C:\wamp64\tmp\php3NOM.tmp
[error] => 0
[size] => 120853
)
We will use temporary upload path [tmp_name] where attachment is uploaded, because we DO NOT want to upload attachment file on server.
$this->email->clear(TRUE); //any attachments in loop will be cleared.
$this->email->from('your#example.com', 'Your Name');
$this->email->to('someone#example.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
//Check if there is an attachment
if ( $_FILES['attach_file']['name']!='' && $_FILES['attach_file']['size'] > 0 )
{
$attach_path = $_FILES['attach_file']['tmp_name'];
$attach_name = $_FILES['attach_file']['name'];
$this->email->attach($attach_path,'attachment',$attach_name);
}
$this->email->send();
use path helper
$this->load->helper('path');
$path = set_realpath('./images/');
on email line
$this->email->attach($path . $your_file);
here i am using phpmailer to send mail
here full code is mention below
$this->load->library('My_phpmailer');
$mail = new PHPMailer();
$mailBody = "test mail comes here2";
$body = $mailBody;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1;// enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true;// enable SMTP authentication
$mail->Host = "ssl://smtp.gmail.com"; // sets the SMTP server
$mail->Port = 465;// set the SMTP port for the GMAIL server
$mail->Username = "YourAccountIdComesHere#gmail.com"; // SMTP account username
$mail->Password = "PasswordComesHere";// SMTP account password
$mail->SetFrom('SetFromId#gmail.com', 'From Name Here');
$mail->AddReplyTo("SetReplyTo#gmail.com", "Reply To Name Here");
$mail->Subject = "Mail send by php mailer";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment($cdnStorage . '/' . $fileName);
$address ='WhomeToSendMailId#gmail.com';
$mail->AddAddress($address, "John Doe");
if (!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
Here Is Full Source Code
$validation_rules = array(
array('field' => 'name', 'rules' => COMMON_RULES),
array('field' => 'email', 'rules' => COMMON_RULES),
array('field' => 'message', 'rules' => COMMON_RULES),
);
$this->validation_errors($validation_rules);
$name = $this->input->post('name');
$email = $this->input->post('email');
$message = $this->input->post('message');
$this->load->library('email');
//upload file
$attachment_file = "";
if (!empty($_FILES) && isset($_FILES["attachment_file"])) {
$image_name = $_FILES["attachment_file"]['name'];
$ext = pathinfo($image_name, PATHINFO_EXTENSION);
$new_name = time() . '_' . $this->get_random_string();
$config['file_name'] = $new_name . $ext;
$config['upload_path'] = "uploads/email/";
$config['allowed_types'] = "*";
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('attachment_file')) {
$finfo = $this->upload->data();
$attachment_file = base_url() . 'uploads/email/' . $finfo['file_name'];
} else {
$error = $this->upload->display_errors();
$this->msg = $error;
$this->_sendResponse(5);
}
}
$this->email->from($email, "$name")
->to("example#gmail.com")
->subject("FeedBack From $name")
->message($message)
->attach($attachment_file);
if ($this->email->send()) {
// temp pass updated.
$this->msg = "Email send successfully.";
$this->_sendResponse(1);
} else {
$this->msg = "Internal server error/Something went wrong.";
$this->_sendResponse(0);
}
$this->load->library('email'); // Loading the email library.
$this->email->clear(TRUE);
$this->email->from($user_email, $name);
$this->email->to('email#gmail.com');
$this->email->subject("Some subject");
$this->email->message("Some message");
if($_FILES['userfile']['name']!='' && $_FILES['userfile'['size'] > 0){
$attach_path = $_FILES['userfile']['tmp_name'];
$attach_name = $_FILES['userfile']['name'];
$this->email->attach($attach_path,'attachment',$attach_name);
}
$this->email->send();
I'm Having a form with the following fields.
Name
Address
Contact
PDF (File Attachment)
This PDF is to be uploaded from the system and send these details together with the uploaded PDF via email. I want these details to be in the custom email template using standalone view and send.
I'm using TYPO3 v7.6.23
I'm new to TYPO3. How to do This?
I'm adding my code here
$addJobsInfo = GeneralUtility::makeInstance('MNU\\MnuJobs\\Domain\\Model\\Jobs');
$addJobsInfo->setName($arguments['name']);
$addJobsInfo->setAddress($arguments['address']);
$addJobsInfo->setContact($arguments['contact']);
$this->jobsRepository->add($addJobsInfo);
$persistenceManager = $this->objectManager->get('TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager');
$persistenceManager->persistAll();
$lastID = $addJobsInfo->getUid();
$getPDF = $_FILES;
if(!empty($getPDF)){
$pdfName = $getPDF['tx_mnujobs_mnujobs']['name']['jobsDOC'];
$pdfTemp = $getPDF['tx_mnujobs_mnujobs']['tmp_name']['jobsDOC'];
$resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
$storage = $resourceFactory->getDefaultStorage();
$folder = $storage->getFolder('user_upload');
$pdfFinalName = 'Jobs_'.time().'_'.$pdfName;
$uploadPDF = $storage->addFile($pdfTemp, $folder, $pdfFinalName);
if($lastID){
$newId = 'NEW'.$lastID;
$data = array();
$data['sys_file_reference'][$newId] = array(
'table_local' => 'sys_file',
'uid_local' => $uploadPDF->getUid(),
'tablenames' => 'tx_mnujobs_domain_model_jobs',
'uid_foreign' => $lastID,
'fieldname' => 'pdfattachment',
'pid' => $this->settings['pageUid']
);
$dataHandler = GeneralUtility::makeInstance(DataHandler::class);
$dataHandler->start($data, array());
$dataHandler->process_datamap();
}
}
//E-mail Sending
$mail = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
$mail->setSubject('Contact Details');
$mail->setTo('sample#gmail.com']);
$mail->setBody('Hi, This is a sample. Please Find the Attachment', 'text/html');
$attachment = Swift_Attachment::fromPath($folder->getIdentifier().$pdfFinalName);
$attachment->setFilename('Document.pdf');
$mail->attach($attachment);
$sendMail = $mail->send();
I'm getting this Exception
Unable to open file for reading
[/user_upload/Jobs_1525757243_sample.pdf]
So I've replaced this
$attachment = Swift_Attachment::newInstance($folder->getIdentifier().$pdfFinalName, 'Document.pdf', 'application/pdf');
$mail->attach($attachment);
Both are not working, Where I've gone wrong?
What worked for me was adding fileadmin in front of the identifier:
$filePath = 'fileadmin' . $file->getOriginalResource()->getIdentifier();
$attachment = \Swift_Attachment::fromPath($filePath);
$mail->attach($attachment);
Use ext:powermail, it is feature rich, actively maintained and very well documented
Parsing an XML feed and save it this way:
$action = new CouponActionForm();
$values = array(
'name' => $offer->name,
'link' => $offer->url,
'description' => $offer->description,
'discount' => $offer->discount,
'price' => $offer->price
);
$files = $this->getImages($offer->picture);
if(!$action->bindAndSave($values, $files)){
echo $action->renderGlobalErrors();
die('BAD THING');
}
Here is the getImages method:
private function getImages($url){
$ret = array('error' => 0);
$tmp_dir = sys_get_temp_dir();
$tmp_file = tempnam($tmp_dir, 'kupon');
if(copy($url, $tmp_file)){
$ret['tmp_name'] = $tmp_file;
$ret['name'] = basename($url);
$ret['size'] = filesize($tmp_file);
$ret['type'] = 'image/jpeg';
return array('filename' => $ret);
}else{
die('HELP');
}
}
Why do I use form saving instead of object saving with ->fromArray method ? Well, I already made the form and all validation, so I don't want to implement the same thing twice (DRY), but as important, I actually don't know how to use validators in doctrine model.
So the problem is that the form doesn't save files in specific directory specified by the path property of sfValidatorFile validator, but it exists in tmp directory.
I'm trying send a email when admin cancel a order manually. I'm using the order_cancel_after event and my observer method run fine.
But my email is not fired. I get the following exception (above), despite all code be run.
exception 'Zend_Mail_Protocol_Exception' with message 'No recipient forward path has been supplied' in /home/mydomain/www/loja/lib/Zend/Mail/Protocol/Smtp.php:309
I tested sending a new email on my order observer: $order->sendNewOrderEmail(), and the new order email arrived correctly, so my SMTP is ok.
My code in observer:
class Spalenza_Cancelorder_Model_Observer
{
public function enviamail(Varien_Event_Observer $observer)
{
$order = $observer->getOrder();
if ($order->getId()) {
try {
$translate = Mage::getSingleton('core/translate');
$email = Mage::getModel('core/email_template');
$template = 16;//Mage::getModel('core/email_template') ->loadByCode('Cancelamento Manual by Denis')->getTemplateId();
Mage::log('Codigo do template: '.$template,null,'events.log');
$sender = array(
'name' => Mage::getStoreConfig('trans_email/ident_support/name', Mage::app()->getStore()->getId()),
'email' => Mage::getStoreConfig('trans_email/ident_support/email', Mage::app()->getStore()->getId())
);
Mage::log($sender,null,'events.log');
$customerName = $order->getShippingAddress()->getFirstname() . " " . $order->getShippingAddress()->getLastname();
$customerEmail = $order->getPayment()->getOrder()->getEmail();
$vars = Array( 'order' => $order );
$storeId = Mage::app()->getStore()->getId();
$translate = Mage::getSingleton('core/translate');
Mage::getModel('core/email_template')
->sendTransactional($template, $sender, $customerEmail, $customerName, $vars, $storeId);
$translate->setTranslateInline(true);
Mage::log('Order successfully sent',null,'events.log');
} catch (Exception $e) {
Mage::log($e->getMessage(),null,'events.log');
}
} else {
Mage::log('Order not found',null,'events.log');
}
}
}
Magento version: 1.5.1.0
This line
$customerEmail = $order->getPayment()->getOrder()->getEmail();
should probably be
$customerEmail = $order->getPayment()->getOrder()->getCustomerEmail();
You should pay attention to what the error message says and check the output of your variables.
please help..I'm newbies and try to learn Zend Framework, but have problem when uploading image.
The script at file Application.ini
uploads.uploadPath = APPLICATION_PATH "/../public/uploads"
Form to upload Image:
$this->setAction('/data/personil/create')
->setMethod('post');
//Item input untuk gambar
$images = new Zend_Form_Element_File('images');
$images->setMultiFile(3)
->addValidator('IsImage')
->addValidator('Size', false, '204800')
->addValidator('Extension', false, 'jpg,png,gif')
->addValidator('ImageSize', false, array(
'minwidth' => 150,
'minheight' => 150,
'maxwidth' => 700,
'maxheight' => 700
))
->setValueDisabled(true);
// attach element to form
$this->addElement($images);
// create display group for file elements
$this->addDisplayGroup(array('images'), 'files');
$this->getDisplayGroup('files')
->setOrder(40)
->setLegend('Images');
Controller action create :
public function createAction()
{
$form = new Pengadilan_Form_PersonilCreate();
$this->view->form = $form;
$flashMessenger = $this->_helper->FlashMessenger;
//SImpan kedatabase
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
$personil = new Pengadilan_Model_Personil();
$personil->fromArray($form->getValues());
$personil->RecordDate = date('Y-m-d', mktime());
$personil->DisplayStatus = 0;
$personil->DisplayUntil = null;
$personil->save();
$id = $personil->RecordId;
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
$form->images->setDestination($config['uploadPath']);
$adapter = $form->images->getTransferAdapter();
for($x=0; $x<$form->images->getMultiFile(); $x++) {
$xt = #pathinfo($adapter->getFileName('images_'.$x.'_'), PATHINFO_EXTENSION);
$adapter->clearFilters();
$adapter->addFilter('Rename', array(
'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
'overwrite' => true
));
$adapter->receive('images_'.$x.'_');
}
$this->_helper->getHelper('FlashMessenger')->addMessage('Data sekses diinput ke database #' . $id . '. Admin akan segera merivew, jika diterima, akan ditampilkan dalam waktu 48 jam, Terima kasih.');
$this->_redirect('/data/personil/sukses');
}
}
}
Controller action display :
public function displayAction()
{
//Pertama setting filters
$filters = array(
'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
);
$validators = array(
'id' => array('NotEmpty', 'Int')
);
$input = new Zend_Filter_Input($filters, $validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$q = Doctrine_Query::create()
->from('Pengadilan_Model_Personil p')
->leftJoin('p.Pengadilan_Model_Jabatan j')
->leftJoin('p.Pengadilan_Model_Tupoksi t')
->leftJoin('p.Pengadilan_Model_Golongan g')
->leftJoin('p.Pengadilan_Model_Agama a')
->leftJoin('p.Pengadilan_Model_Kelamin k')
->where('p.RecordId = ?', $input->id)
->addWhere('p.DisplayStatus = 1')
->addWhere('p.DisplayUntil >= CURDATE()');
$result = $q->fetchArray();
if(count($result) == 1){
$this->view->personil = $result[0];
$this->view->images = array();
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
foreach (glob("{$config['uploadPath']}/{$this->view->item['RecordID']}_*") as $file) {
$this->view->images[] = basename($file);
}
}else{
throw new Zend_Exception('Maaf, halaman tidak ditemukan, 404');
}
}else{
throw new Zend_Exception('Kesalahan Input');
}
}
The last script at view : display.phtml
<div id="images">
<?php foreach ($this->images as $image): ?>
<img src="/uploads/<?php echo $this->escape($image); ?>" width="150" height="150" />
<?php endforeach; ?>
Image upload Destination at config is /public/uploads
in my case image at /public
Image succes to upload and renamed but outside the directory and
Image won't displayed at display.phtml
Many thanks for your help..
First you need to set your form encoding File element link$form->setAttrib('enctype', 'multipart/form-data');
Also you should probably finish setting up your image element before you POST the form not after. So move the setDestination stuff up to where you initialize the form, you may have a better chance of it working.
public function createAction()
{
$form = new Pengadilan_Form_PersonilCreate();
//set form encoding
$form->setAttrib('enctype', 'multipart/form-data');
//get path and set destination for image element
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
$form->images->setDestination($config['uploadPath']);
$this->view->form = $form;
//consider intializing flash messenger in the init() method
$flashMessenger = $this->_helper->FlashMessenger;
//SImpan kedatabase
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
//more code...
$adapter = $form->images->getTransferAdapter();
for($x=0; $x<$form->images->getMultiFile(); $x++) {
$xt = #pathinfo($adapter->getFileName('images_'.$x.'_'), PATHINFO_EXTENSION);
$adapter->clearFilters();
$adapter->addFilter('Rename', array(
'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
'overwrite' => true
));
$adapter->receive('images_'.$x.'_');
}
$this->_helper->getHelper('FlashMessenger')->addMessage('Data sekses diinput ke database #' . $id . '. Admin akan segera merivew, jika diterima, akan ditampilkan dalam waktu 48 jam, Terima kasih.');
$this->_redirect('/data/personil/sukses');
}
}
}
not sure if this will fix everything but it should be a start...