使用 Cakephp 3 发送电子邮件

问题描述 投票:0回答:1

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

https://github.com/PHPMailer/PHPMailer

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

无效地址:(发件人):XXX 数组 ( [错误] => 1 [消息] => 邮件错误: 无效地址: (发件人): XXX )

我做了什么:禁用 Gmail 的两步验证

并启用允许打开不太安全的应用程序

PagesController.php

<?php
namespace App\Controller;

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

public function index()
{
        $to = '[email protected]';
    $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;   

}
}

电子邮件组件.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!");
    }
}
}
php email cakephp gmail
1个回答
0
投票

已修复,我必须更换

EmailComponent 中的那三行

$sender = "[email protected]";
$mail->Username   = "[email protected]";
$mail->Password   = "GMAIL_PASSWORD";
© www.soinside.com 2019 - 2024. All rights reserved.