Since getServices() is deprecated, I spent some time trying to send mail without it.
The code below works, and with real emails, the email arrives, but there’s a strange quirk:
use MODX\Revolution\Mail\modPHPMailer;
$sender = '[email protected]';
$recipient = '[email protected]';
if (!$modx->services->has('mail')) {
$modx->services->add('mail', new modPHPMailer($modx));
}
$mail = $modx->services->get('mail');
$mail->set(modMail::MAIL_BODY, 'Testing Mail Service again');
$mail->set(modMail::MAIL_FROM, $sender);
$mail->set(modMail::MAIL_FROM_NAME, 'Bob');
$mail->set(modMail::MAIL_SENDER, $sender);
$mail->set(modMail::MAIL_SUBJECT, 'TESTING');
$mail->address('to', $recipient);
$mail->address('reply-to', $sender);
$mail->setHTML(true);
if (!$sent = $mail->send()) {
$err = 'Error: ' . $mail->mailer->ErrorInfo;
$this->modx->log(xPDO::LOG_LEVEL_ERROR, $err);
$mail->reset();
return 'Failure';
} else {
$mail->reset();
return "Mail sent";
}
The quirk is that the mail
class in the Pimple container is:
PHPMailer\PHPMailer\PHPMailer#22
(the number varies). I tried stepping through the code in XDebug, but couldn’t find where this happens.
This doesn’t happen with any of the other services. So is the code correct, why does this happen, and is it an issue?
As a side note, as far as I can tell, the mail service is never initialized anywhere in MODX 3. All the places that send mail (e.g., modUser
) are using getService()
, and all the MODX 3 docs I could find advise using getService()
.
I also found that calling $mail->reset()
threw a 500 error on MODX cloud. Commenting it out made the code work, and uncommenting it produced the 500 error (did this cycle several times). That seems to have gone away after manually clearing the site cache, so maybe it’s not an issue. It’s pretty mysterious, though, since reset() is quite innocuous. It just empties the mail fields.