Drupal8: Send E-mail after node creating.

This CodeLet Sends an email after a node of specific content type is created. The CodeLet uses Drupal8 API which sends and email upon node creation. This CodeLet implement hook_entity_insert & hook_mail.
Place this CodeLet on your MYMODULE.module file.


//Add this line to the top of the MYMODULE.module file.
use Drupal\Component\Utility\SafeMarkup;

* Implements hook_mail().
function MYMODULE_mail($key, &$message, $params) {
$options = array(
'langcode' => $message['langcode'],

switch ($key) {
case 'node_insert_alert':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('Ticket created: @title', array('@title' => $params['node_title']), $options);
$message['body'][] = SafeMarkup::checkPlain($params['message']);

* Implements hook_entity_insert().
function MYMODULE_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {

if ($entity->getEntityTypeId() !== 'node' || ($entity->getEntityTypeId() === 'node' && $entity->bundle() !== 'CONTENT_TYPE')) {

$mailManager = \Drupal::service('plugin.manager.mail');

$module = 'MYMODULE';
$key = 'node_insert_alert';
$to = 'To mail '; // email to be sent to this Email ID

$params['message'] = "Message";

$params['node_title'] = $entity->label();
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;

$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($result['result'] !== true) {
$message = t('There was a problem sending alert email notification to @email for creating ticket @id.', array('@email' => $to, '@id' => $entity->id()));
//drupal dblog
\Drupal::logger('MYMODULE alert')->error($message);

$message = t('An email notification has been sent to @email for creating node @id.', array('@email' => $to, '@id' => $entity->id()));
//drupal dblog
\Drupal::logger('MYMODULE alert')->notice($message);

By saru1683 on Tue, 05/01/2016 - 11:15am

Add comment

Log in or register to post comments

Try GSuite and get 20% discount for first year