问题
In my CakePHP application I have an email form I have made myself that opens when an email hyperlink is clicked. How do I then pass the data from the form so that it can be sent using CakeEmail? Sorry, I've tried this for ages and checked through all the documentation on http://book.cakephp.org/2.0/en/core-utility-libraries/email.html, still can't figure it out.
Here is my code...
email.ctp
<?php $this->Html->addCrumb('New Email', '#'); ?>
<div id="email_page" class="span12">
<div class="row">
<?php
echo $this->Form->create('Email', array('controller'=>'person', 'action'=>'email_send'));
echo $this->Form->input('email', array('class'=>'email_form','label'=>'To: ','value'=>$email['Person']['primEmail']));
echo $this->Form->input('subject', array('class'=>'email_form','label'=>'Subject: '));
echo $this->Form->input('message', array('class'=>'email_form email_body', 'type'=>'textarea','label'=>'Message: '));
echo $this->Form->end('Send', array('class'=>'pull-right'));
?>
</div>
</div>
email_send.php
<?php
$email = new CakeEmail('default');
$email->to('email');
$email->subject('subject');
$email->send('message');
?>
Any help is appreciated!
回答1:
Form data will be available in the Controller in $this->request->data
(writable) or $this->data
(readable). As your form is called Email all data will be available under $this->request->data['Email']
after the form is submitted.
I'm not sure why you would have the email code in email_send.php
instead of using a Controller method. The form expects an email_send
method present in the PersonsController, as the form action is set to /persons/email_send
. So I would place the email code inside email_send()
in PersonsController.php
.
So:
<?php
public function email_send() {
$email = new CakeEmail('default');
$email->to($this->request->data['Email']['email']);
$email->subject($this->request->data['Email']['subject']);
$email->send($this->request->data['Email']['message']);
}
?>
Of course, when all this is working, you should set up proper validation and check if $this->request->data
is populated with the relevant data.
回答2:
A better optimised code would be in
public function email()
{
//add this
if ($this->request->is('post')) {
$post_array = $this->request->data;
$email = new CakeEmail();
$email->viewVars(array('message' => $post_array['Email']['message'] ))
->template('contactForm')
->emailFormat('html')
->config(array('from' => 'test@test.com' ,'to' => $post_array['Email']['email']))
->subject ($post_array['Email']['subject'])
->send();
}
}
This is in general you can define an email template with name of contact_form.ctp under
/app/View/Emails/html/
and pass the data to templete and format the html as per your requirement. thanks!
来源:https://stackoverflow.com/questions/13490250/sending-email-with-cakeemail