I'm trying to create an email component/model that will add an email to the database (with certain fields like, to, from, subject, message, created, modified, etc).
AFTER the data has been sucessfully saved (which it currently does), I'd like to actually send the message.
I figure this would be easiest with an afterSave() function, but I cannot get the email to send.
Here is some relevant code:
Email Model
<?php
class Email extends AppModel {
var $name = 'Email';
var $displayField = 'subject';
function afterSave() {
$this->Email->to = $this->data['Email']['email'];
$this->Email->subject = $this->data['Email']['subject'];
$this->Email->replyTo = $this->data['Email']['email'];
$this->Email->from = 'Private Message <' . $this->data['Email']['email'] . '>';
//$this->Email->template = 'simple_message';
$this->Email->send($this->data['Email']['email_text']);
}
}
add.ctp for email
<div class="universities form">
<?php echo $this->Form->create('Email');?>
<fieldset>
<legend><?php __('Add Email'); ?></legend>
<?php
echo $this->Form->input('subject');
echo $this->Form->input('email_text');
echo $this->Form->hidden('email', array('value' => $this->params['named']['contact_email']));
echo $this->Form->hidden('user_from', array('value' => $this->Session->read('User.id')));
echo $this->Form->hidden('created', array('value' => date("Y-m-d")));
echo $this->Form->hidden('modified', array('value' => date("Y-m-d")));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
Controller save code:
function add() {
if (!empty($this->data)) {
$this->Email->create();
// pr($this->data);
// die;
if ($this->Email->save($this->data)) {
$this->Session->setFlash(__('The email has been saved', true));
} else {
$this->Session->setFlash(__('The email could not be saved. Please, try again.', true));
}
}
}
Error I am getting on trying to send:
Fatal error: Call to undefined method stdClass::send() in /Users/[USER]/Sites/example_app/app/models/email.php on line 14
New Controller Code:
function add() {
if (!empty($this->data)) {
$this->Email->create();
// pr($this->data);
// die;
if ($this->Email->save($this->data)) {
$this->Session->setFlash(__('The email has been saved', true));
function _sendMail() {
$this->Email->to = $this->data['Email']['email'];
$this->Email->subject = $this->data['Email']['subject'];
$this->Email->replyTo = $this->data['Email']['email'];
$this->Email->from = 'Private Message <' . $this->data['Email']['email'] . '>';
$this->Email->sendAs = 'text'; //Send as 'html', 'text' or 'both' (default is 'text')
$email->send();
}
$this->_sendMail();
} else {
$this->Session->setFlash(__('The email could not be saved. Please, try again.', true));
}
}
}
components are meant to be used in a controller, not the model - so the cleanest way is to send the mail from controller when $this->Model->save() returns true.
Because you did name your Model "Email", i dont think you can use the component "Email" the standard way and need to load it manually:
In the controller (function add())
if ($this->Email->save($this->data)) {
// save was successfull
App::import('Component', 'Email');
$email = new EmailComponent();
$email->startup($this);
$email->from='joe#example.com';
$email->to = $this->data['Email']['email'];
$email->subject = $this->data['Email']['subject'];
$email->replyTo = $this->data['Email']['email'];
$email->from = 'Private Message <' . $this->data['Email']['email'] . '>';
$email->sendAs = 'text'; //Send as 'html', 'text' or 'both' (default is 'text')
$email->send();
$this->Session->setFlash(__('The email has been saved', true));
}
Nevertheless it is possible to send mails from the model, see the second answer of this (duplicate) thread:
How do I use the email component from a model in CakePHP?
Related
I'm new to the zend framework.
I have a code to send a mail and it's working, but the message is not received by the customer side, but it returns that the mail was sent successfully. Can you teach me how to work with zend_email?
public function sendMailStatements($qid,$emails=array()) {
require_once 'Zend/Mail.php';
require_once 'Zend/Mail/Transport/Smtp.php';
try {
$config = array('ssl' => 'ssl',
'port' => 465,
'auth' => 'login',
'host' => '127.0.0.1',
'username' => 'username#gmail.com',
'password' => 'password');
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
Zend_Mail::setDefaultTransport($transport);
$mail = new Zend_Mail();
$mail->setSubject("Quotation LL Sports Exim");
$body="Dear Sir/Madam<br>Kindly find the attached Quotation and give us your Feed BAck";
$mail->setBodyHtml($body);
foreach ($emails as $email):
$mail->addTo($email);
endforeach;
var_dump($emails);
if($qid!=""):
$fullBaseUrl = getcwd();
$full_path = $fullBaseUrl . "\\pdfs\\" .$qid.".pdf";
$content = file_get_contents($full_path); // e.g. ("attachment/abc.pdf")
$attachment = new Zend_Mime_Part($content);
$attachment->type = 'application/pdf';
$attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$attachment->encoding = Zend_Mime::ENCODING_BASE64;
$attachment->filename ="quotation.pdf"; // name of file
$mail->addAttachment($attachment);
endif;
$mail->send($transport);
return true;
} catch (Zend_Exception $e) {
echo "Caught exception: " . get_class($e) . "\n";
echo "Message: " . $e->getMessage() . "\n";
exit;
// Other code to recover from the error
}
}
Please let me know where I did wrong?
Thanks in advance.
Hai i want to insert my form fields into database and retrive records from database in moodle. how to do that :
Here is my form what i created :
Uplo.php
<?php
require_once('config.php');
require_once("$CFG->libdir/formslib.php");
class uplo extends moodleform {
public function definition() {
global $CFG;
$mform = $this->_form;
$buttonarray=array();
$mform->addElement('text', 'name', get_string('name'));
$mform->setType('name', PARAM_NOTAGS);
$mform->setDefault('name', 'Please enter name');
$mform->addElement('text', 'email', get_string('email'));
$mform->setType('email', PARAM_NOTAGS);
$mform->setDefault('email', 'Please enter email');
$buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
$buttonarray[] = &$mform->createElement('cancel');
$mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
$mform->closeHeaderBefore('buttonar');
}
function validation($data, $files) {
return array();
}
}
?>
Testing.php:
<?php
define('_DB_HOST_NAME','localhost');
define('_DB_USER_NAME','root');
define('_DB_PASSWORD','');
define('_DB_DATABASE_NAME','moodle_test');
$dbConnection = mysqli_connect(_DB_HOST_NAME,_DB_USER_NAME,_DB_PASSWORD,_DB_DATABASE_NAME);
?>
<?php
require_once('uplo.php');
$mform = new uplo();
$mform->display();
if(isset($_POST['submitbutton'])){
$name = $mform->get_data('name');
$email = $mform->get_data('email');
$table='insert';
$res=insert_record($table, $name,$email, $returnid=true, $primarykey='id') ;
}
?>
This one is i tried. how to do that in a right way
Make sure you require_once(dirname(FILE).'/../../config.php') (adjust the number of '/../' based on the subdirectory your file is in, relative to config.php).
The use the Moodle data manipulation API https://docs.moodle.org/dev/Data_manipulation_API
Im trying to secure my Zend form with crsf token. Allways if I add token element to my form, it always send me back notEmpty error message for token. Im I doing something wrong? Thx
class Application_Form_Test3 extends Zend_Form {
public function init() {
$this->setMethod('post');
//..some elements
$note = new Zend_Form_Element_Textarea('note');
$note->addValidator('stringLength', false, array(2, 50));
$note->setRequired(true);
$note->class = 'form-control';
$note->setLabel('Poznámka:');
$note->setAttrib('placeholder', 'poznamka ke spisu');
$note->setOptions(array('cols' => '20', 'rows' => '4'));
$submit = new Zend_Form_Element_Submit('submit');
$submit->class = 'btn btn-success';
$submit->setValue('odeslat');
$this->addElements(array(
$number,
$year,
$owner,
$note,
$submit,
));
$this->addElement('hash', 'no_csrf_foo', array('salt' => 'unique'));
}
}
Action in controller:
public function findAction() {
$request = $this->getRequest();
$form = new Application_Form_Test3();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
var_dump($request->getPost());
} else {
var_dump("ERROR");
}
}
$this->view->form = $form;
}
In my view I render form and dump error messages
...
<?php echo $form->renderForm(false); ?>
...
//render single elements here
//eg. <?php echo $form->note->renderViewHelper(); ?>
...
<?php var_dump($form->getMessages()) ?>
...
After each validation of form, i get array of error messages like that:
array(2) { ["note"]=> array(1) { ["isEmpty"]=> string(36) "Value is required and can't be empty" } ["no_csrf_foo"]=> array(1) { ["isEmpty"]=> string(36) "Value is required and can't be empty" } }
if I fill good values to elements, the last one error is always for token - NotEmpty, so my form is never valid.
Problem solved. I didnt render token element in my View so i added to View:
<?php echo $form->no_csrf_foo->renderViewHelper(); ?>
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.
As the title says, I tried calling the receive() function either of Form Element and the Adapter Object(not one after another of course). I printed the returned value - was 1 in both cases - which means receive() returned true.
The file was not found on the server though. I tried setting encrypt type of zend form to multipart/form-data - didn't help.
I'm totally clueless so any info is welcomed.
Calling receive() on transfer adapter: file location and upload name are constants.
$this->uploadName = $uploadName;
$this->upload = new Zend_File_Transfer_Adapter_Http();
$this->upload->setDestination($this->fileLocation);
...
$val = $this->upload->receive();
$quoteName = $this->upload->getFileName($this->uploadName);
$size = $this->upload->getFileSize($this->uploadName);
calling receive on form element:
//form creation - my form extends zend form
$staticForm = Srm_Form::getForm(my form,null,null,
my config);
$staticForm->setEnctype('multipart/form-data');
$staticForm->getElement(my file element name)->setDestination(my dest);
//calling receive
$form = Srm_Form::getForm(my form,null,null,my config);
$form->setEnctype('multipart/form-data');
if(!$form->isValid($_POST)){
print_r($form->getMessages());
}
// echo $form->getElement(my file element)->getValue();
$val = $form->getElement(my file element)->receive();
echo "bbbbbb".$val;
I should add that this code works when it is called after the file element is added to the form manually and not through use of a config file.
Okay, the problem was found -
The destination was not set for the file element (it was set manually for the transfer adapter in other place)when handling the submitted form.
I define a simple form with the Zend_Form_Element_File element
<?php
class Form_UploadForm extends Zend_Form
{
public function __construct($options = null)
{
parent::__construct($options);
$this->setMethod('post');
$this->setAttrib('enctype', 'multipart/form-data');
$decors = array(
array('ViewHelper'),
array('HtmlTag'),//array('tag'=>'table')),
array('Label', array('separator' => ' ')), // those unpredictable newlines
array('Errors', array('separator' => ' ')), // in the render output
);
$file = new Zend_Form_Element_File('file');
$file->setDestination('/a/b/c/upload');
$file->setLabel('Document File Path')
->setRequired(true)
->addValidator('NotEmpty');
$this->addElement($file);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Upload File');
$this->addElement($submit);
}
}
?>
My action method in the Controller is
function uploadAction()
{
$this->view->pageTitle = "Zend_Form File Upload Example";
$this->view->bodyCopy = "<p>Please fill out this form.</p>";
$form = new Form_UploadForm();
if ($this->_request->isPost())
{
$formData = $this->_request->getPost();
if ($form->isValid($formData))
{
try
{
$form->file->receive();
}
catch (Zend_File_Transfer_Exception $e)
{
throw new Exception('unable to recieve : '.$e->getMessage());
}
$uploadedData = $form->getValues();
//Zend_Debug::dump($form->file->getFileName(), 'tmp_file');
$this->processFile($form->file->getFileName());
}
else
{
$form->populate($formData);
}
}
$this->view->form = $form;
}
Note - i don't call the Zend_File_Transfer_Adapter_Http directly
The final piece is the view
<?php echo $this->form; ?>