Score:0

What is a good way to send out email notifications on creation of a new entity?

hk flag

I was trying to see what is the best way to handle customized notifications around the Website Feedback module. The module creates a new entity of type WebsiteFeedback (a custom entity defined by the module) whenever a user submits feedback using the module

I see Entity Notifications module but that does not seem to have a Drupal 9 release.

Is there something ready for Drupal 9?

Jaypan avatar
de flag
The Rules module should do this for you.
apaderno avatar
us flag
I’m voting to close this question because it's asking for recommendations or suggestions on hosting, books, tools, modules, themes, distributions, tutorials, or other off-site resources.
fr flag
A solution using Rules is documented here: https://www.drupal.org/docs/8/modules/d8-rules-essentials/examples/email-examples/sending-html-email All you have to do is import that Rule and use the UI to modify it slightly for your use case.
Score:1
cn flag

If you want to code it yourself, here's a simple example for emailing a notification every time a Comment entity is posted (taken from an actual site with minor cleanup, but I might have broken something pulling out the site-specific code):

function mymodule_comment_insert(Comment $entity) {
  mymodule__mail_notify_admin('new_comment', $entity, '', 'insert');
}

function mymodule_mail_notify_admin($key, $entity, $title, $moderation_state) {
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'mymodule';
  $to_email = '[email protected]';
  $path = $entity->toUrl('canonical', ['absolute' => TRUE])->toString();
  $params['message'] = $path;
  $params['title'] = $title;
  $params['moderation_state'] = $moderation_state;
  $langcode = \Drupal::currentUser()->getPreferredLangcode();

  $result = $mailManager->mail($module, $key, $to_email, $langcode, $params);
  if ($result['result'] !== TRUE) {
    $message = t('Error sending email notification to @email.', ['@email' => $to_email]);
    \Drupal::logger('mymodule')->error($message);
    return;
  }
  else {
    $message = t('Email notification sent to @email', ['@email' => $to_email]);
    \Drupal::logger('mymodule')->notice($message);
  }
}

/*
 * For reference:
 * http://valuebound.com/resources/blog/how-to-send-mail-programmatically-drupal-8
 */
function mymodule_mail($key, &$message, $params) {
  $message['from'] = \Drupal::config('system.site')->get('mail');

  switch ($key) {
    case 'new_comment':
      // https://www.drupal.org/project/simple_comment_email_notification
      $message['subject'] = t('New comment');
      $message['body'][] = t('You can check the page at :unapprovedCommentsUrl for unapproved comments and :publishedCommentsUrl for published comments.', [
        ':unapprovedCommentsUrl' => \Drupal::request()->getSchemeAndHttpHost() . '/admin/content/comment/approval',
        ':publishedCommentsUrl'  => \Drupal::request()->getSchemeAndHttpHost() . '/admin/content/comment',
      ]);
      break;

    default:
      $options = [
        'langcode' => $message['langcode'],
      ];
      // @todo Fix HTML escaping.
      // $message['body'][] = Html::escape($params['message']);.
      $message['body'][] = $params['message'];
      $message['subject'] = t('@title @ms on my site',
        [
          '@ms' => $params['moderation_state'],
          '@title' => $params['title'],
        ],
        $options);
      break;
  }
}
fr flag
Rules gives you a way to do the exact same thing without writing and maintaining your own code. Plus with Rules you have a UI which will allow you to easily modify the workflow if your needs evolve. Plus, with Rules you don't have to worry about writing your own email code, which can be bug-prone and complicated. For example, want to use HTML in your emails? Not with the above code ... Rules is like Views, but for workflow. Sure you can write your own custom code query the database to display anything you want, but Views is easier to use and maintain for most use cases. Likewise with Rules.
cn flag
@anonymous Sure, Rules is one solution. But some people don't want to trust a module that has only had an alpha version for the entire Drupal 8 lifecycle. For some people, security coverage matters.
fr flag
And what's so secure about custom code vs. code that is being used/tested by thousands of sites? Attitudes like that are why most modules go straight to a "stable" release even though they have no tests, no upgrade path between "stable" versions, and have BC-breaking changes between minor point releases. There's nothing "stable" about them except the name, and by any other name they would stink just as bad (apologies to Shakespeare). It pays to be an educated consumer, and if you are judging just based on whether the release is "stable" then you're deceiving yourself. The word has no meaning.
cn flag
I didn't say "stable", I said **security coverage**. Alpha module = not subject to the drupal.org security disclosure policy. Been in alpha for what, six years now? And could have a zero-day disclosed at any time.
cn flag
Rules is a complicated module and opens up a huge attack surface if all you need it for is to send some emails. Not saying it's the wrong approach, but it's definitely not automatically the safest, most secure approach to install an alpha module.
fr flag
Obviously I disagree, but this is not the place to discuss it. However, you're totally wrong when you say Rules doesn't have security coverage - it DOES.
cn flag
@anonymous I'm happy to be corrected if I said something factually incorrect. Could you please give me a link to where it says Rules for D8/9 has security coverage? I just checked the Rules module page and it says `Stable releases for this project are covered by the security advisory policy.` This is just drupal.org boilerplate, but there's no mention of a special exception of security coverage for Rules.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.