I have some code for send to mail but it's not working properly.
My code is here:
class EmailsController extends AppController
{
var $name="Email";
var $uses = NULL;
public function index()
{
App::import('Component', 'Email');
$path=WWW_ROOT."img";
$filename="Desert.jpg";
$email->from = 'pal#gmail.com';
$email->to='abc#gmail.com';
$email->subject='test mail';
$email->template = 'simple_message';
$email->attachments = array($path.$filename);
$email->SendAs='html';
if($email->send())
{
$this->session->setFlash("Email Send Successfully");
}
else
{
$this->session->setFlash("Email is not send");
}
}
}
I am getting the error like:
Call to undefined method stdClass::send()
Why don't you use var $components? Include Email component the right way:
class EmailsController extends AppController
{
var $name="Email";
var $components = array('Email');
var $uses = NULL;
public function index() {
$path=WWW_ROOT."img";
$filename="Desert.jpg";
$this->Email->from = 'pal#gmail.com';
$this->Email->to='abc#gmail.com';
$this->Email->subject='test mail';
$this->Email->template = 'simple_message';
$this->Email->attachments = array($path.$filename);
$this->Email->sendAs='html';
if($this->Email->send()) {
$this->Session->setFlash("Email Send Successfully");
} else {
$this->Session->setFlash("Email is not send");
}
}
}
For more info please visit: http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
<?php
App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail( $smtp );
$email->to( 'test#example.com' );
$email->subject(__("Reset Password") );
$email->emailFormat('html');
$email->send($body);
?>
For SMTP:
save this below code with "email.php" file in app/Config folder and put your smtp details in $smtp array. and assign $smtp variable in
new CakeEmail($smtp);
<?php
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'My Site'),
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
?>
Related
I have written generating email functionality inside public function add().
My idea is to send my to the users who had registered.
my add functionality looks like this.
add functionality is working fine but mail generation giving error says Unknown email configuration "gmail". Any help please.
app/Controller/UsersController.php
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$data[] = $this->request->data;
foreach($data as $row){
$email_name = $row['User']['username'];
$password = $row['User']['password'];
}
$data = array();
$subject = "Visualization Tool Login credentials";
// From
$header="manasasirsi17#gmail.com";
// Your message
$message="welcome user\r\n";
$message.="Thank You for Registering\r\n";
$message.="your login details are as given below\r\n";
$message.="username:$email_name\r\n";
$message.="password:$password\r\n";
App::uses('CakeEmail', 'Network/Email');
$smtp = new CakeEmail('smtp');
$smtp->from(array($header => $header));
$smtp->to($email_name);
$smtp->subject($subject);
$smtp->emailFormat('html');
$Email->send($message);
$this->Session->setFlash(__('Login Details are sent to You via Email.'));
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
}
app/Config/email.php
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'host' => 'ssl://smtp.gmail.com',
'port' => 25,
'timeout' => 30,
'username' => 'manasasirsi17#gmail.com',
'password' => 'secure',
'client' => null,
'log' => false
);
public $fast = array(
'from' => 'you#localhost',
'sender' => null,
'to' => null,
'cc' => null,
'bcc' => null,
'replyTo' => null,
'readReceipt' => null,
'returnPath' => null,
'messageId' => true,
'subject' => null,
'message' => null,
'headers' => null,
'viewRender' => null,
'template' => false,
'layout' => false,
'viewVars' => null,
'attachments' => null,
'emailFormat' => null,
'transport' => 'Smtp',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => true,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
You've not defined a gmail email config in your EmailConfig class. This line:-
$Email = new CakeEmail('gmail');
should be from the looks of your code:-
$Email = new CakeEmail('smtp');
The parameter you pass to CakeEmail determines which of the defined configs in EmailConfig you want to use. If you had wanted to pass it gmail you would have needed to add a $gmail property to the EmailConfig class containing the configuration.
I am working in cakephp and want to send confirmation link on user signup but i do not know much about SMTP.
Here is What i have written I am using Token to confirm email which will expire next time if user hit the same confirmation link.
Here is usercontroller/signup method:
public function signup()
{
$this->layout = 'main';
if ($this->request->is('post')) {
$this->User->create();
$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
$hash = sha1($this->request->data['User']['username'] . rand(0, 100));
$this->request->data['User']['tokenhash'] = $hash;
if ($this->User->validates()) {
$this->User->save($this->request->data);
$ms = 'Click on the link below to complete registration ';
$ms .= 'http://localhost/FindTutor/users/verify/t:' . $hash . '/n:' . $this->data['User']['username'] . '';
$ms = wordwrap($ms, 70);
$this->Email->from = 'usman.jamil0308#gmail.com';
$this->Email->to = $this->request->data['User']['email'];
$this->Email->subject = 'Confirm Registration..';
$this->Email->send($ms);
$this->Session->setFlash('Please Check your email for validation Link');
$this->redirect('/users/login');
}
}
}
Here is users/verify method to confirm if user hit the confirmation link.
public function verify(){
//check if the token is valid
if (!empty($this->passedArgs['n']) && !empty($this->passedArgs['t'])){
$name = $this->passedArgs['n'];
$tokenhash = $this->passedArgs['t'];
$results = $this->User->findByUsername($name);
if ($results['User']['activate']==0){
//check the token
if($results['User']['tokenhash']==$tokenhash)
{
$results['User']['activate']=1;
//Save the data
$this->User->save($results);
$this->Session->setFlash('Your registration is complete');
$this->redirect('/users/login');
exit;
}
else{
$this->Session->setFlash('Your registration failed please try again');
$this->redirect('/users/register');
}
}
else {
$this->Session->setFlash('Token has alredy been used');
$this->redirect('/users/register');
}
}else
{
$this->Session->setFlash('Token corrupted. Please re-register');
$this->redirect('/users/register');
}
}
Error is somthing like this:
mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
try to use mailjet and configure your sever (wamp or xampp)the directorie sendmail and configure your app.php like that
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => '',
'password' => '',
'client' => null,
'tls' => null,
],
'mailjet' => [
'className' => 'smtp',
// The following keys are used in SMTP transports
'host' => 'in-v3.mailjet.com',
'username' => 'copy that from your account mailjet',
'password' => 'copy that from your account mailjet',
'port' => 587,
'timeout' => 3000,
'client' => null,
'tls' => null,
],
],
'Email' => [
'default' => [
'transport' => 'mailjet',
'from' => 'xxxxxx#gmail.com',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
],
public $smtp = array(
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'your email id',
'password' => 'your password',
'transport' => 'Smtp',
);
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail('smtp');
$Email->from('info#email.com');
$Email->to($email);
$message = "hello";
$Email->send($message);
First Include Email Component in your App Controller like this :
public $components = array(
'Email'
);
Create a sendMail function in your App controller like this
public function _sendMail( $to, $from, $replyTo, $subject, $element,$parsingParams = array(),$attachments ="", $sendAs = 'html', $bcc = array()){
$port = '';
$timeout = '';
$host = '';
$username = '';
$password = '';
$client = '';
$toAraay = array();
if (!is_array($to)) {
$toAraay[] = $to;
} else {
$toAraay = $to;
}
$this->Email->smtpOptions = array(
'port' => "$port",
'timeout' => "$timeout",
'host' => "$host",
'username' => "$username",
'password' => "$password",
'client' => "$client"
);
$this->Email->delivery = 'smtp';
foreach ($parsingParams as $key => $value) {
$this->set($key, $value);
}
foreach ($toAraay as $email) {
$this->Email->to = $email;
$this->Email->subject = $subject;
$this->Email->replyTo = $replyTo;
$this->Email->from = $from;
if(!empty($bcc)){
$this->Email->cc = $bcc[0];
}
if ($attachments!="") {
$this->Email->attachments = array();
$this->Email->attachments[0] = $attachments ;
}
$this->Email->template = $element;
$this->Email->sendAs = $sendAs;
$this->Email->send();
$this->Email->reset();
}
}
Create a sendmail.ctp file in View/Emails/html
Add this content in file and also add your header or footer
<?php echo $message; ?>
Now whenever you want to send email call this function like this :
$this->_sendMail($to, $from, $replyTo, $subject, 'sendmail', array('message' => $message), "", 'html', $bcc = array());
Now you can implement your logic for verification email like this :
$message = 'Click on the link below to complete registration ';
$message .= 'http://localhost/FindTutor/users/verify/t:' . $hash . '/n:' . $this->data['User']['username'] . '';
$from = 'usman.jamil0308#gmail.com';
$to = $this->request->data['User']['email'];
$subject = 'Confirm Registration..';
$replyTo = 'usman.jamil0308#gmail.com';
$this->_sendMail($to, $from, $replyTo, $subject, 'sendmail', array('message' => $message), "", 'html', $bcc = array());
I'm having hard time with a weird behaviour of fileinput.
This is my form:
namespace Frontend\Form;
use NW\Form\Form;
use Zend\InputFilter;
use Zend\Form\Element;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class EnrollStructure extends Form implements ServiceManagerAwareInterface
{
protected $sm;
public function __construct($name=null) {
parent::__construct("frmEnrollStructure");
$this->setAttribute("action", "/registrazione_struttura/submit")
->setAttribute('method', 'post')
->setAttribute("id", "iscrizione_struttura")
->setAttribute("class", "form fullpage");
$this->addInputFilter();
}
public function init()
{
$structureFs = $this->sm->get('Structure\Form\Fieldsets\Structure');
$structureFs->setUseAsBaseFieldset(true);
$structureFs->remove("id")
->remove("creationTime")
->remove("latLon");
$file = new Element\File("images");
$file->setAttribute('multiple', true);
$this->add($structureFs)->add($file);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Iscriviti',
'id' => 'sbmtEnrollStructure',
'class' => 'submit_btn'
),
));
$this->setValidationGroup(
array(
'structure' =>
array(
'companyname',
'vatNumber',
'addressStreet',
'addressZip',
'addressCity',
'addressRegion',
'fax',
'publicPhone',
'publicEmail',
'website',
'status',
'ownerNotes',
'category',
'subcategory',
"facilities",
"agreeOnPolicy",
"agreeOnPrivacy",
"subscribeNewsletter",
"contact" => array("name", "surname", "email", "role", "phone"),
),
"images"
));
}
/**
* Set service manager
*
* #param ServiceManager $serviceManager
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->sm = $serviceManager;
}
public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
// File Input
$fileInput = new InputFilter\FileInput('images');
$fileInput->setRequired(true);
$fileInput->getValidatorChain()
->attachByName('filesize', array('max' => "2MB"))
->attachByName('filemimetype', array('mimeType' => 'image/png,image/x-png,image/jpg,image/jpeg'))
->attachByName('fileimagesize', array('maxWidth' => 2048, 'maxHeight' => 2048));
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
}
Basically, I mainly use a fieldset which contains most of the data I request to the user, plus a File input field.
This is the Fieldset Structure: (most important parts..)
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Validator\Identical;
use Zend\Validator\NotEmpty;
use Zend\Validator\Regex;
use Zend\Validator\StringLength;
class Structure extends Fieldset implements InputFilterProviderInterface, ServiceManagerAwareInterface
{
protected $sm;
public function __construct()
{
parent::__construct('structure');
}
public function init()
{
$this->setHydrator(new DoctrineHydrator($this->_entityManager(),'Structure\Entity\Structure'));
$this->setObject($this->sm->getServiceLocator()->get("Structure_Structure"));
$id = new Element\Hidden("id");
$name = new Element\Text("companyname");
$name->setLabel("Ragione Sociale");
...........
}
public function getInputFilterSpecification()
{
return array
(
"id" => array(
"required" => false,
),
"companyname" => array(
"required" => true,
"validators" => array(
array('name' => "NotEmpty", 'options' => array("messages" => array( NotEmpty::IS_EMPTY => "Inserire la ragione sociale")))
),
),
.....
}
}
This is my controller:
public function submitAction()
{
try {
$this->layout("layout/json");
$form = $this->getForm('Frontend\Form\EnrollStructure');
//$form->addInputFilter();
$structure = $this->getServiceLocator()->get("Structure_Structure");
$viewModel = new ViewModel();
$request = $this->getRequest();
if ($request->isPost())
{
$post = array_merge_recursive
(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid())
{
$structure = $form->getObject();
$contact = $structure->getContact();
$this->getServiceLocator()->get('Structure_ContactService')->save($contact);
$files = $request->getFiles()->toArray();
if(isset($files['images']))
{
$count = 3;
foreach($files['images'] as $pos => $file)
{
$fpath = $this->getServiceLocator()->get('RdnUpload\Container')->upload($file);
if(!empty($fpath))
{
if(--$count ==0) break;
$asset = $this->getServiceLocator()->get("Application_AssetService")->fromDisk($fpath, $file['name']);
$this->getServiceLocator()->get("Application_AssetService")->save($asset);
$structure->addImage($asset);
}
}
}
$this->getServiceLocator()->get('Structure_StructureService')->save($structure);
$retCode = RetCode::success(array("iscrizione_struttura!" => array("form_submit_successfull")), true);
}
else
{
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
}
$viewModel->setVariable("retcode", $retCode);
return $viewModel;
}
} catch(Exception $e)
{
throw $e;
}
}
The strange thing is that if i remove from the field "images" the "multiple" attribute everything works fine, causing the form not to validate and i get this message:
[images] => Array
(
[fileUploadFileErrorFileNotFound] => File was not found
)
While, if i set the attribute multiple, and the user does not upload a file i get no error, but the form gets invalidated (this is the reason for this "bad" code in my controller:)
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
I found the problem was caused by the Jquery form plugin, without it it works fine. :( In case somebody needs, I think the correct action code can be found here (I haven't tryied it anyway)
https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Controller/ProgressExamples.php
I'm having problems sending a mail with cakephp2, I know I can send emails because I have my postfix configured, and I can send e-mails with command line or php. So please, can you send me an example of cakephp2 sending emails.
This is the error message
Invalid email: "you#localhost"
Error: An Internal Error Has Occurred.
I've also tried with the ssl via gmail and it doesn't work either, and it's giving me a really hard time.
thanks guys
by the way, I'm trying the exact example of this url http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
Your app/config/Email.
class EmailConfig {
public $gmail = array(
'port' => '465',
'timeout' => '300',
'host' => 'ssl://smtp.gmail.com',
'username' => '<your_email>#gmail.com',
'password' => '<you_password>',
'transport' => 'Smtp'
); }
your file = app/controller/appController.php insert this function
public function sendEmail($type, $options){
try {
$Email = new CakeEmail($type);
$Email->config($options);
$Email->template = "email_confirmation";
$Email->emailFormat('html');
//$this->idCrudRash = $options;
$Email->send();
} catch (SocketException $e) {
die('Erro ao enviar email:'. $e->getMessage());
$this->log(sprintf('Erro ao enviar email: %s', $e->getMessage()));
}
}
for user: app/controller/contato.php
$options = array(
'emailFormat' => 'html',
'from' => array(
$config['email_noanswer'] => $config['site_name']
),
'subject' => 'Confirmação de Cadastro',
'to' => $this->request->data['User']['email'],
//'template' => 'default',
'template' => 'email_confirmation',
'viewVars' => array(
'title_for_layout' => 'Confirmação de Email ' . $config['site_name'],
'name' => $this->request->data['User']['name'],
'email' => $this->request->data['User']['email'],
//'cpf' => base64_encode($this->request->data['User']['cpf']),
'site_name' => $config['site_name'],
),
);
$this->sendEmail('gmail', $options);
In your email.php file, please remove the default 'from' value, it overrides your passed param.
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost', // remove this line
...
);
In app/config/Email
public $smtp = array(
'transport' => 'Smtp',
'from' => array('no-reply#xyz.com' => 'no-reply#xyz.com'),
'host' => 'ssl://smtp.abc.com',
'port' => 465,
'timeout' => 30,
'username' => 'username',
'password' => 'password',
'client' => null,
'log' => false,
);
In Your Controller
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
public function index()
{
$this->layout = 'layout';
$this->set('title', "Title");
if ($this->request->is('Post')) {
if (!empty($this->request->data)) {
if ($this->Modal->Save($this->request->data)) {
$to = 'test#anc.com';
$subject = 'Your_subject';
$message = $this->request->data;
if ($this->sendmail($to, $subject, $message)) {
echo"sent";die;
}
} else {
echo"wrong";die;
}
}
}
}
public function sendmail($to = null, $subject = '', $messages = null, $ccParam = null, $from = null, $reply = null, $path = null, $file_name = null)
{
$this->layout = false;
$this->render(false);
$name = $messages['Modalname']['name'];
$email = $messages['Modalname']['email'];
$Email = new CakeEmail();
$Email->config('smtp');
$Email->viewVars(array('name' => $name, 'email' => $email));
$Email->template('comman_email_template', 'comman_email_template');
return $Email->emailFormat('html')
->from(array('no-reply#xyz.com' => 'no-reply#xyz.com'))
->to($to)
->subject($subject)
->send();
}
Create a layout and view for email template.and add the data value that have been sent.
I've come across a strange error in CakePHP when sending a contact form to a recipient via e-mail. When a contact form is filled out and is submitted, CakePHP then sends the e-mail to recipient absolutely fine. But instead of sending one email once it seems to send two emails at the same time.
My controller code is this:
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
$this->layout = 'modal';
if(isset($this->data['Contact'])) {
$userName = $this->data['Contact']['yourname'];
$userPhone = $this->data['Contact']['yourtelephone'];
$userEmail = $this->data['Contact']['youremail'];
$userMessage = $this->data['Contact']['yourquestion'];
$email = new CakeEmail();
$email->viewVars(array(
'userName' => $userName,
'userPhone' => $userPhone,
'userEmail' => $userEmail,
'userMessage' => $userMessage
));
$email->subject(''.$userName.' has asked a question from the website');
$email->template('expert', 'standard')
->emailFormat('html')
->to('recipient-email#gmail.com')
->from('postman#website.co.uk', 'The Postman')
->send();
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
And this is the code for the contact form:
<?php
echo $this->Form->create('Contact', array('url' => '/contact/ask-the-expert/', 'class' => 'contact'));
echo $this->Form->input('yourname', array(
'type' => 'text',
'label' => 'Your Name <span class="star">*</span>',
));
echo $this->Form->input('yourtelephone', array(
'type' => 'text',
'label' => 'Your Telephone',
));
echo $this->Form->input('youremail', array(
'type' => 'text',
'label' => 'Your Email <span class="star">*</span>',
));
echo $this->Form->input('yourquestionAnd ', array(
'type' => 'textarea',
'label' => 'Your Question <span class="star">*</span>',
));
echo $this->Form->submit();
echo $this->Form->end();
?>
Cheers!
Put your Mail Send code inside if ($this->request->is('post')) {} and try.
UPDATE
updated the code.
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
$this->layout = 'modal';
if(isset($this->data['Contact'])) {
$userName = $this->data['Contact']['yourname'];
$userPhone = $this->data['Contact']['yourtelephone'];
$userEmail = $this->data['Contact']['youremail'];
$userMessage = $this->data['Contact']['yourquestion'];
$email = new CakeEmail();
$email->viewVars(array(
'userName' => $userName,
'userPhone' => $userPhone,
'userEmail' => $userEmail,
'userMessage' => $userMessage
));
$email->subject(''.$userName.' has asked a question from the website');
$email->template('expert', 'standard')
->emailFormat('html')
->to('recipient-email#gmail.com')
->from('postman#website.co.uk', 'The Postman')
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}