How to send mail programmatically in Drupal 8

How to send mail programmatically in Drupal 8

Sometime we require emails to be sent on certain events e.g. for a blog website or a news site we may need to send email after creating new article or blog or in case of e-commerce site we may need to send  confirmation mail after successful completion of an order. In this article we are going to explore how we can use Mail API in Drupal 8 programmatically for sending emails.
Here we will be looking on how to send the email after successful creation of article.

Sending email in Drupal is a two steps process:

  • Define your email properties (like subject, body, headers, etc.) in an appropriate hook_mail() implementation.
  • Use Mail manager to send email

Step 1:

When we send an email programmatically, we need to specify the module name that implements hook_mail().

Now lets see how do we implement it.


This is a simple implementation that defines one template identified as test_message (the $key). The other two function arguments are:

$message: passed by reference, and inside which we add as much boilerplate about our email as we need

$params: an array of extra data that needs to go in the email and that is passed from the mail manager when we try to send the email

This was all about implementation of hook_mail().

Step 2 : Using Mail manager to send email

This will gets triggered every time any Article will be created.

Every time when we will create any Article, we load the Drupal Mail manager service and start setting values for email. We need the following information:

  • $module : the module name that implements hook_mail() and defines our template
  • $key : the template id
  • $to :the recipient email address (the one found on the current user account)
  • $langcode :the language which goes inside the $params array and which will be used to translate the subject message
  • $params['subject'] : email subject
  • $params['message'] the email body
  • $send : the boolean value indicating whether the email should be actually sent

We then pass all these values to the mail() method of the mail manager. The latter is responsible for building the email (calling the right hook_mail() implementation being one aspect of this) and finally delegating the actual delivery to the responsible plugin. By default, this will be PHPMail, which uses the default mail() function that comes with PHP.
And this is all about sending emails programmatically using Drupal 8. We have seen the steps required to send email programmatically by the mail manager whenever we want it. We have also mentioned the default mail delivery plugin which is used to send emails in Drupal 8.

Source :


Advance Your Business: Drupal 8 Support Ends - Take Action!