【问题标题】:Sending Mail using CakePHP 3.0使用 CakePHP 3.0 发送邮件
【发布时间】:2014-12-10 02:06:44
【问题描述】:

我正在使用 CakePHP 框架的新版本 3.0 开发一个网站。我在本地主机上工作,想在用户填写表格后发送电子邮件。以下是我的控制器中用于发送电子邮件的代码。

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 的类,但我不知道如何使用它来调试我的代码。有人用过吗?

【问题讨论】:

  • 我认为您不能在本地主机中使用 email(),尝试将其上传到实时站点。 :) 顺便说一句,我记得我的朋友可以使用 localhost xampp 发送电子邮件,也许这取决于您的 apache 或其他东西。 :)
  • 你可以使用 smtp 从 localhost 发送邮件
  • 请务必提及您的确切 CakePHP 版本!如果您使用的是最近的 3.x 版本,那么这应该会失败,但会出现有关丢失传输的异常。此外,您的代码缺少 from() 调用的结束 (,请确保您的实际代码中不存在此问题。话虽如此,请查看how to configure a transport 上的文档以了解电子邮件类(注意:基本用法部分缺少该部分)。
  • 从 localhost 发送电子邮件还有更多选项,例如:Mailgun、Mandrill 等

标签: email cakephp


【解决方案1】:

大家好,谢谢大家的回答。

通过使用 mailjet.com,我能够在 localhost 中发送电子邮件。下面是不同的步骤:

步骤 1

在 mailjet 网站上创建一个帐户

第二步

在 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'
    ]
],

第三步

在你的控制器中

<?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";

        }


    }
}

【讨论】:

    【解决方案2】:

    您必须使用 SMTP 服务器从配置电子邮件中的本地主机发送电子邮件。

    有两种方法可以实现:

    1. 在带有邮件配置的真实服务器上使用它

    2. 使用 SMTP 服务器在本地主机上进行测试。有很多 SMTP 服务器供您使用。 见mailjet.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2013-09-06
      相关资源
      最近更新 更多