0

我正在为我正在开发的项目使用 Laminas 框架。我安装了 Node.js 以使用 maildev 作为 SMTP 服务器,通过 PHPMailer 发送邮件,一切运行良好。下一步是使用 Laminas 框架 laminas-cli 创建脚本,这个也可以正常工作。问题是,在我的脚本执行结束时,我想向用户发送电子邮件,但我收到了这个错误:

附加参数:-fnanguisamuel@gmail.com 2022-01-19 19:44:06
结果:false 2022-01-19 19:44:06 无法实例化邮件功能。2022-01-19 19:44:06 使用 mail() 发送 2022-01-19 19:44:06 发送邮件路径:2022-01-19 19:44:06 信封发件人:nanguisamuel@gmail.com 2022-01- 19 19:44:06 至:nanguisamuel@gmail.com 2022-01-19 19:44:06 主题:TEST LAMINAS 2022-01-19 19:44:06 标题:日期:2022 年 1 月 19 日星期三 19:44: 06 +0000 发件人:nanguisamuel@gmail.com 回复:nanguisamuel@gmail.com 邮件 ID:<bYYlElEH6jBVhViNmZY2Mpqd6EteZ1DLZKbNDK1O4@DESKTOP-D4AB8IN> X-Mailer:PHPMailer 6.5.3 ( https://github.com/PHPMailer/PHPMailer) MIME 版本:1.0 内容类型:text/html;charset=UTF-8 内容传输编码:base64 2022-01-19 19:44:06 附加参数:-fnanguisamuel@gmail.com

我不得不说,当我从我的控制器调用我的自定义类函数时,我在我的本地主机页面中收到了 maildev 的电子邮件,但从控制台我什么也没得到。这是我的代码片段:

我的 ConsoleGenerationRelances 命令:

<?php

declare(strict_types=1);

namespace Commun\Scripts;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;

class ConsoleGenerationRelances extends Command
{
    /** @var string */
    private $mapper;
    private $cronEnv;    
    private $MAIL;    
    protected static $defaultName = 'console-generation-relances';
    
    public function __construct($mapper=[],$cronEnv=[],$MAIL=NULL){
        $this->mapper = $mapper;
        $this->cronEnv = $cronEnv;        
        $this->MAIL = $MAIL;        
        parent::__construct();
    }

    protected function configure() : void
    {
        $this->setName(self::$defaultName);
        //$this->addOption('name', null, InputOption::VALUE_REQUIRED, 'Module name');
    }

    protected function execute(InputInterface $input, OutputInterface $output) : int
    {
        $mapperAbonnementPrestation = $this->mapper['mapperAbonnementPrestation'];
        $relances = $mapperAbonnementPrestation->getDataRelancesForConsole();        
        $output->writeln('Démarrage du script des relances |~>  : '.date('Y-m-d H:i:s'));
        $nbreJourAvantRelance = $this->cronEnv['cron'];  
        //$output->writeln(json_encode($this->MAIL));
        foreach ($relances as $relance){            
            if(empty($nbreJourAvantRelance) || empty($relance['dateLimitePaiement']) ){         // Si parametre de relance non defini alors on saute l'execution       
                continue;
            }
            $now = strtotime(date('Y-m-d H:i:s')); // or your date as well
            $dateLimitePaiement = strtotime($relance['dateLimitePaiement']);
            $datediff = $now-$dateLimitePaiement;
            $nombreJour = abs(round($datediff / 86400));            
            if($nombreJour<=$nbreJourAvantRelance){ // On envoie le mail
               //sleep(10); //$this->MAIL->envoiMailCreationCompte(['emailTo'  => ['nanguisamuel@gmail.com'],'nomPrenoms'  => 'Samuel NANGUI','motDePasse'  => 'test']); //On envoie un mail au user avec ses parametres                              
                $this->MAIL->test(['nanguisamuel@gmail.com']);
            }
        }
        $output->writeln('Fin du script des relances |~>  : '.date('Y-m-d H:i:s'));
        return 0;
    }
}

我的 ConsoleGenerationRelances 工厂

<?php

declare(strict_types=1);

namespace Commun\Scripts\Factory;

use Commun\Scripts\ConsoleGenerationRelances;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\Factory\FactoryInterface;
use Commun\Controller\Plugin\NslabsMail;
use Commun\Scripts\Mail\CronMail;
class ConsoleGenerationRelancesFactory implements FactoryInterface
{
    /**
     * @param ContainerInterface $container
     * @param string $requestedName
     * @param null|array $options
     * @return $requestedName Entity
     */
        
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {        
        $mappers = ['mapperAbonnementPrestation' => $container->get('TABONNEMENTPRESTATION')]; 
        $mailConfig = $container->get('config')['sendMailParameters'];
        $host = $mailConfig['host'];
        $smtpSecure = $mailConfig['smtpSecure'];
        $port = $mailConfig['port'];
        $debug = $mailConfig['debug'];
        $smtpAuth = $mailConfig['smtpAuth'];
        $username = $mailConfig['username'];
        $password = $mailConfig['password'];
        $useSMTP = $mailConfig['useSMTP'];           
        return new ConsoleGenerationRelances($mappers,
                                             $container->get('config'),
                                             new CronMail(new NslabsMail($host,$smtpSecure,$port,$debug,$smtpAuth,$username,$password,$useSMTP))
                                            );
        
    }     
}

我的自定义 CronMail 类如下:

<?php

/**
    * @module     Commun
    * @subpackage Scripts/Mail
    * @author     Samuel NANGUI <nanguisamuel@gmail.com>
    * @copyright  Copyright (c) 2022 Nslabs
    */

namespace Commun\Scripts\Mail; 
use Commun\Controller\Plugin\NslabsMail;


class CronMail
{
    
    
    protected $classMail;

    function __construct(NslabsMail $_classMail)
    {
        $this->classMail = $_classMail;        
    }
    
    
    public function test($to){
        $this->classMail->ajouterDestinataire($to);
        $this->classMail->ajouterReplyTo('nanguisamuel@gmail.com');
        $this->classMail->ajouterExpediteur('nanguisamuel@gmail.com');
        $message = $this->classMail->enteteEmail()
                .'Cher/Chère SAM,<br/><br/>'
                ."Ca marche avec PHP MAILER.<br/><br/>"                                 
                ."<br/><br/>"                                    
                .$this->classMail->ajoutSignature(); 
                
        try{
            $this->classMail->setMessage('TEST LAMINAS', $message);
            $this->classMail->send();               
        } catch (\Exception $e){
            //var_dump($e->getMessage());
            //die();
        }
        $this->classMail->clearAllAddressesAndAttachments();
    }
       
    public function envoiMailCreationCompte($params){
        
        $this->classMail->ajouterDestinataire($params['emailTo']);
        $this->classMail->ajouterReplyTo('nanguisamuel@gmail.com');
        $this->classMail->ajouterExpediteur(EXPEDITEUR_MAIL_GENERAL);
        $this->classMail->ajouterDestinaireCopieCarbone(['nanguisamuel@gmail.com']);
        $message = $this->classMail->enteteEmail()
                .'Cher/Chère ' . $params['nomPrenoms'] . ',<br/><br/>'
                ."Nous avons le plaisir de vous informer de la création de votre compte utilisateur avec le mot de passe suivant : ".$params['motDePasse']." <br/><br/>"                 
                ."Nous vous recommandons de le changer dès votre première connexion a la platefome.<br/>"                                           
                ."<br/><br/>"                                      
                .$this->classMail->ajoutSignature(); 
                
        try{
            $this->classMail->setMessage('['.PORTAIL.'] Confirmation de création de compte utilisateur', $message);
            $this->classMail->send();            
        } catch (\Exception $e){
            //var_dump($e->getMessage());
            //die();
        }
        $this->classMail->clearAllAddressesAndAttachments();
        
    }    
}

最后是我的 NslabsMail 类:

<?php

/**
    * @module     Commun
    * @subpackage Controller/Plugin
    * @author     Samuel NANGUI <nanguisamuel@gmail.com>
    * @copyright  Copyright (c) 2020 Nslabs
    */

namespace Commun\Controller\Plugin; 

Use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require APPLICATION_PATH.'/vendor/autoload.php';

class NslabsMail extends PHPMailer
{
           
   /*private $host;
   private $smtpAuth;
   private $username;
   private $password;
   private $smtpSecure;
   private $port;
   private $debug;*/
   
   public function __construct($host='localhost',$smtpSecure=PHPMailer::ENCRYPTION_SMTPS,$port=25,$debug=SMTP::DEBUG_SERVER,$smtpAuth=FALSE,$username=NULL,$password=NULL,$useSMTP=FALSE,$exceptions=null) {
       parent::__construct($exceptions);
       
       $this->Host = $host;
       $this->SMTPAuth = $smtpAuth;
       if($smtpAuth){
            $this->Username = $username;
            $this->Password = $password;
       }       
       $this->SMTPSecure = $smtpSecure;
       $this->Port = $port;       
       $this->SMTPDebug  = $debug; 
       $this->CharSet = 'UTF-8';
       $this->Encoding = 'base64';
       if($useSMTP){
          $this->isSMTP(); 
       }else{
          $this->isMail(); 
       }                  
   }
   
   public function clearAllAddressesAndAttachments(){
       $this->clearAddresses();
       $this->clearAllRecipients();
       $this->clearAttachments();
       $this->clearBCCs();
       $this->clearReplyTos();
       $this->clearCCs();
   }
   
   public function ajouterExpediteur($email,$username=''){
       $this->setFrom($email, $username);
   }
   
   public function ajouterDestinataire($adressesDestinataire=[]){
        if(empty($adressesDestinataire)){
           throw new Exception("Aucun destinaire précise");
        }
        foreach ($adressesDestinataire as $adresse){            
            $this->addAddress($adresse, !empty($adresse['username']) ? $adresse['username'] : '');
        }
   }
   
   public function ajouterDestinataireCopie($adressesCC=[]){
       if(!empty($adressesCC)){
           foreach ($adressesCC as $adresse){
               $this->addCC($adresse, !empty($adresse['username']) ? $adresse['username'] : '');
           }
       }
   }
   
   public function ajouterReplyTo($email){
       $this->addReplyTo($email);
   }
   
   
   public function ajouterDestinaireCopieCarbone($adressesBCC=[]){
        if(!empty($adressesBCC)){
           foreach ($adressesBCC as $adresse){
               $this->addBCC($adresse, !empty($adresse['username']) ? $adresse['username'] : '');
           }
        }
   }
   
   
   public function ajouterPiecesJointes($attachments=[]){
       if(!empty($attachments)){
           foreach ($attachments as $file){
               $this->addAttachment($file);
           }           
       }
   }
   
   
   public function setMessage($subject='',$message='',$isHTML=TRUE){
       $this->Subject = $subject;
       $this->Body = $message;
       $this->isHTML($isHTML);
   }
    
    
   public function enteteEmail() {        
       $str = 
       '<div style="width:600px;">'.    
       '<div style="font-family:Arial;font-size:11px;">'.  
       //'<img style="margin-bottom:5px" src="'.$racine_site.'/'.$baseUrl->baseUrl('/img/logo/logo-dgi-email.png').'"><br />'.    
       '<span style="color:#fdd116;font-size:18px;font-weight:bold">'.PORTAIL.'</span>
        <p style="color:#009177;">
        Ceci est un email envoyé automatiquement par '.PORTAIL.'.<br/> 
        </p>
        <hr style="color:#009177;">
        <br/>
        </div>'
        .'<div style="font-family:Arial;">'
        ;        
        return $str;
        
    }
    
    
    public function ajoutSignature() {
        
       $str = 
       '</div>'. // ouvert dans l'entete    
       '<br/>'.    
       '<br/>'.    
       '<div style="font-family:Arial;font-size:11px;">'. 
       '<span style="font-size:16px;font-weight:bold;margin-bottom:5px;">'.NSLabs.'</span><br/>'.
       '<span style="font-size:14px;font-weight:bold;color:#d03630;">'.PORTAIL.'</span>'.
       '<p style="margin-top:10px;color:grey;">Pour nous contacter :<br/>'.
       '<span style="font-weight:bold;color:grey;">Tél   : '.SIGNATURE_MAIL_TELEPHONE    .'</span><br/>'.
       '<span style="font-weight:bold;color:grey;">Email : '.SIGNATURE_MAIL_EMAIL_CONTACT.'</span><br/>'.
       '<br/>'.
       SIGNATURE_MAIL_ADRESSE1.'<br/>'.             
       '</p>'.
       $this->warningNoRetour().
       '</div>'.    
       '</div>'    
       ;
        
        return $str;
        
    }
    
    
    public function warningNoRetour() {
        
       $str = 
       '<hr>'.    
       '<span style="font-size:14px;font-weight:bold;color:red">Attention aux emails frauduleux ! </span><br/>'.
       '<p style="color:red;">
       Pour votre sécurité, ne répondez jamais à un e-mail vous demandant vos identifiants de connexion et/ou vos comptes de paiement, <br/>
       et/ou vous informant d’un changement vos identifiants de connexion.'.
       '</p>'
        ;
        
        return $str;
        
    }
}

任何帮助将不胜感激

4

0 回答 0