Email 使用CakePHP 3.0发送邮件
我正在用CakePHP框架的新版本3.0开发一个网站。我正在使用localhost,希望在用户填写表单后发送电子邮件。下面是我的控制器中发送电子邮件的代码Email 使用CakePHP 3.0发送邮件,email,cakephp,Email,Cakephp,我正在用CakePHP框架的新版本3.0开发一个网站。我正在使用localhost,希望在用户填写表单后发送电子邮件。下面是我的控制器中发送电子邮件的代码 public function index(){ if ($this->request->is('post'){ $email = new Email(); $email->from([$this->request->data["sender"] => "Sender"]
public function index(){
if ($this->request->is('post'){
$email = new Email();
$email->from([$this->request->data["sender"] => "Sender"]
->to("myEmail@hotmail.com")
->subject($this->request->data["Subject"])
->send($this->request->data["message"]);
}
}
当执行此代码时,我的邮箱中没有任何事件、错误和消息。我看到cakephp3.0中存在一个名为
DebugTransport
的类,但我不知道如何使用它来调试代码。有人已经使用了它?您必须使用SMTP服务器从配置电子邮件中的本地主机发送电子邮件
有两种方法可以实现这一点:
嗨,谢谢大家的回答 通过使用mailjet.com,我能够在localhost中发送电子邮件。以下是不同的步骤: 第一步 在mailjet网站上创建帐户 步骤2 在app.php中,在EmailTransport表中添加一个新条目。可以在mailjet网站上找到不同的参数主机、端口、用户名和密码
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'tls' => null,
],
'mailjet' => [
'host' => 'in-v3.mailjet.com',
'port' => 587,
'timeout' => 60,
'username' => 'xxxxx',
'password' => 'xxxxx',
'className' => 'Smtp'
]
],
步骤3
在控制器中
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Network\Email\Email;
class ContactController extends AppController {
var $helpers = array('Html');
public function index(){
if($this->request->is('post')){
$userName = $this->request->data['firstname'] . " " . $this->request->data['lastname'];
$email = new Email();
$email->transport('mailjet');
try {
$res = $email->from([$this->request->data['email'] => $userName])
->to(['myEmail@hotmail.com' => 'My Website'])
->subject('Contact')
->send($this->request->data['message']);
} catch (Exception $e) {
echo 'Exception : ', $e->getMessage(), "\n";
}
}
}
我认为您不能在本地主机中使用电子邮件(),请尝试将其上载到实时站点。:)顺便说一句,我记得我的朋友可以使用localhost xampp发送电子邮件,这可能取决于您的apache或其他版本。:)您可以使用smtp从LocalHost发送邮件。请始终提及您的确切CakePHP版本!如果您使用的是最新的3.x版本,那么这将很难失败,因为缺少传输。此外,您的代码缺少一个结束语(
对于from()
调用,请确保您的实际代码中不存在此问题。尽管如此,请检查电子邮件类的文档(注意:基本用法部分缺少该部分)。从本地主机发送电子邮件有更多选项,例如:Mailgun、Mandrill等