1 year ago
#71816
Samuel N.
Could not instanciate mail function with PhpMailer
I'm using Laminas framework for a project I'm developing. I installed Node.js to use maildev as SMTP server for sending mail e-mails with PHPMailer and everything is working well. The next step is to create scripts with Laminas framework laminas-cli and this one also works fine. The problem is that at the end on the execution of my script, I would like to send e-mail to the user and I'm getting this error :
Additional params: -fnanguisamuel@gmail.com 2022-01-19 19:44:06
Result: false 2022-01-19 19:44:06 Could not instantiate mail function. 2022-01-19 19:44:06 Sending with mail() 2022-01-19 19:44:06 Sendmail path: 2022-01-19 19:44:06 Envelope sender: nanguisamuel@gmail.com 2022-01-19 19:44:06 To: nanguisamuel@gmail.com 2022-01-19 19:44:06 Subject: TEST LAMINAS 2022-01-19 19:44:06 Headers: Date: Wed, 19 Jan 2022 19:44:06 +0000 From: nanguisamuel@gmail.com Reply-To: nanguisamuel@gmail.com Message-ID: <bYYlElEH6jBVhViNmZY2Mpqd6EteZ1DLZKbNDK1O4@DESKTOP-D4AB8IN> X-Mailer: PHPMailer 6.5.3 (https://github.com/PHPMailer/PHPMailer) MIME-Version: 1.0 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: base64 2022-01-19 19:44:06 Additional params: -fnanguisamuel@gmail.com
I have to say that when I call my custom class function with from my controllers, I get the e-mail in my localhost page for maildev but from the console I do not get anything. Here are my code snippets :
My ConsoleGenerationRelances command :
<?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;
}
}
Factory of my 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))
);
}
}
My Custom CronMail class below :
<?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();
}
}
And finally my NslabsMail Class :
<?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;
}
}
Any help will be very appreciated
console
phpmailer
zend-framework3
laminas
laminas-dependency-plugin
0 Answers
Your Answer