使用Cakephp 3发送电子邮件

时间:2018-06-17 00:10:12

标签: email cakephp gmail

我一直在用这个库发送邮件

https://github.com/PHPMailer/PHPMailer

但我没有收到电子邮件发送

地址无效:(来自):XXX 数组([错误] => 1 [消息] =>邮件程序错误:地址无效:(来自):XXX)

我做了什么:禁用2步验证到Gmail

启用允许安全性较低的应用

PagesController.php

<?php
namespace App\Controller;

class PagesController extends AppController
 {
public $components = array("Email");

public function index()
{
        $to = 'myemail@gmail.com';
    $subject = 'Hi buddy, i got a message for you.';
    $message = 'Nothing much. Just test out my Email Component using PHPMailer.';

    try {
        $mail = $this->Email->send_mail($to, $subject, $message);
        print_r($mail);
    } catch (Exception $e) {
        echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
    }
    exit;   

}
}

EmailComponent.php

<?php
namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Core\App;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require ROOT. '/vendor/phpmailer/phpmailer/src/Exception.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/SMTP.php';

class EmailComponent extends Component {

public function send_mail($to, $subject, $message)
{
    // date_default_timezone_set('Asia/Calcutta');

    $sender = "XXX"; // this will be overwritten by GMail

    $header = "X-Mailer: PHP/".phpversion() . "Return-Path: $sender";

    $mail = new PHPMailer();

    $mail->SMTPDebug  = 2; // turn it off in production
    $mail->IsSMTP();
    $mail->Host = "smtp.gmail.com"; 
    $mail->SMTPAuth = true;
    $mail->Username   = "XXX";  
    $mail->Password   = "XXX";
    $mail->SMTPSecure = "tls"; // ssl and tls
    $mail->Port = 587; // 465 and 587

    $mail->SMTPOptions = array (
        'tls' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ),
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

    $mail->From = $sender;
    $mail->FromName = "From Me";

    $mail->AddAddress($to);

    $mail->IsHTML(true);
    $mail->CreateHeader($header);

    $mail->Subject = $subject;
    $mail->Body    = nl2br($message);
    $mail->AltBody = nl2br($message);

    // return an array with two keys: error & message
    if(!$mail->Send()) {
        return array('error' => true, 'message' => 'Mailer Error: ' . $mail->ErrorInfo);
    } else {
        return array('error' => false, 'message' =>  "Message sent!");
    }
}
}

1 个答案:

答案 0 :(得分:0)

修正了我必须更换

在EmailComponent中输了三行

$sender = "xxx@gmail.com";
$mail->Username   = "xxx@gmail.com";
$mail->Password   = "GMAIL_PASSWORD";