Send Mail from MODx Template

1.3k views Asked by At

I'm trying to send an email from a MODx template, either just using PHPmail or with MODx's ModMail class. Needless to say neither way is working.

I'm writing the code in a MODx snippet, and including that snippet in my template. When using PHPmail, and with the form action omitted (so that the form submits to the current URL), the page refreshes but no mail is sent.

When I try to use ModMail, nothing happens at all. But I'm not quite sure how to actually call the send mail code in this case, so the code is just sitting there doing nothing.

This is my PHPmail attempt:

<?php
  $to      = $_POST['email'];
  $name    = $_POST['name'];
  $query = $_POST['message'];
  $subject = "Query from " . $name;
  $message = "You're received a query from " . $name . ", their email address is " . $to . ".\r\nThey said:\r\n" . $query;
  $headers = 'From: [email protected]' . "\r\n" .
             'Reply-To: [email protected]' . "\r\n" .
             'X-Mailer: PHP/' . phpversion();

  echo $to;
  echo $name;
  echo $query;
  echo $subject;
  echo $message;
  echo $headers;

  mail($to, $subject, $message, $headers);

?>

And this is with ModMail:

<?php
$message = $_POST['message'];

$modx->getService('mail', 'mail.modPHPMailer');
$modx->mail->set(modMail::MAIL_BODY,$message);
$modx->mail->set(modMail::MAIL_FROM,'[email protected]');
$modx->mail->set(modMail::MAIL_FROM_NAME,'Johnny Tester');
$modx->mail->set(modMail::MAIL_SUBJECT,'Check out my new email template!');
$modx->mail->address('to','[email protected]');
$modx->mail->address('reply-to','[email protected]');
$modx->mail->setHTML(true);
if (!$modx->mail->send()) {
    $modx->log(modX::LOG_LEVEL_ERROR,'An error occurred while trying to send the email: '.$modx->mail->mailer->ErrorInfo);
}
$modx->mail->reset();
2

There are 2 answers

0
Jako On

There is a MODX extra available called QuickEmail, that could check the internal mail functionality.

0
Guido Gallenkamp On

I do all the email handling via the MODX extra FormIt. Look at the rtm for it, it is quite easy to get running. It can handle a lot of the stuff you want to do and prevent (like spam, multisubmit) when having a form.

https://docs.modx.com/extras/revo/formit/formit.tutorials-and-examples/formit.examples.simple-contact-page

Don't try and invent a new solution. Most stuf can be done by using or extending existant MODX extras.