Using and Extending the Drupal 8 Mail API: Part 1

In this two part series we are going to explore the Mail API in Drupal 8. In doing so, we are going to cover two main aspects: how to use it programatically for sending emails and how to extend it for using an external service like Mandrill.

To demonstrate this, in the first part we will create a custom email template that gets used for sending emails to the current user when s/he saves a new Article node. Additionally, we will see how others can alter that template in order to allow for HTML rendering of the email body instead of the default plain text.

In the second part we are going to look at extending the mail system and integrating an external API for email delivery. For this, we will use Mandrill and its PHP library that provides a good foundation for interacting with its API.

All the work we go through can be found in this Git repository as part of a custom Drupal 8 module that we will start writing here. So feel free to check that out if you want to follow along. Let's get started.

The first prerequisite of this module is its .info file:

d8mail.info.yml:

With this out of the way, we can already enable the module on our site if we want.

How Do We Send an Email?

There are two main steps needed to send an email programatically with Drupal 8. We first need to implement hook_mail() in order to define one or more email templates. The second step is to use the mail manager to send emails using one of these templates.

Although called a hook, hook_mail() is not a typical hook but more of a regular function that generally gets called only by the same module that implements it. In other words, when you send an email programatically, you need to specify the module name implementing hook_mail() and the template id you want to use and that is defined by this hook. But we'll see that in a minute. First, how do we implement it?

d8mail.module:

This is a very simple implementation that defines one template identified as node_insert (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

As you can see, we are building up the $message array with values we want this email to include in all the calls. We are setting a default from value that is retrieved from the configuration system and that represents the main site email address. We set a boilerplate email subject that lets the recipient know a new node was created, followed by the name of the node (which will be passed in through the $params array). The subject is also translatable into the language that gets passed from the caller. 

Lastly, we run the message body through the string sanitiser because the text may contain HTML and it might get truncated if we don't encode the HTML elements. And since we are using the SafeMarkup class, we need to use it at the top:

Additionally, the message body is an array that will later be imploded into a string. And obviously there are many other parameters we can set, such as headers, but this will suffice for this example.

And that's all for the hook_mail() implementation. Now let's turn to the code which gets run every time a new node is created, hook_entity_insert():

This hook gets triggered after every node save, and all we have to do is make sure we are targeting the correct node and include our logic.

After checking that the node entity is of the type article, we load the Drupal mail manager service and start setting some values for the email. We need the following information:

  • the module name that implements hook_mail() and defines our template (what I mentioned above)
  • the template id (the $key)
  • the recipient email address (the one found on the current user account)
  • the language ($langcode) which goes inside the $params array and which will be used to translate the subject message
  • the node title that will get added to the email subject
  • the email body, which in our case will be the value of the node's body field
  • 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.

If the mail manager is successful in sending the email (actual delivery is not taken into account but rather a successful PHP action), the mail() method will return an array containing a result key with whatever the mail plugin returns. Checking for that value, we can learn whether the email action was successful and inform the user that we have notified them of their action. Otherwise, we print and log an error message.

And that's about it. Clearing the cache and creating an article node should land an email in your inbox. If you are not getting anything and there are no error signs on your screen, make sure you check your server logs and mail queue to verify that emails are being sent out.

Before moving on, I would like to make a quick note regarding this hook implementation. In this example, I placed all the logic inside it directly. Additionally, I used an early return at the top, which essentially means no other logic can be added but the one specific to the article nodes. In real applications I recommend refactoring the mailing logic into a separate function or class and deferring to that. Moreover, you should not use early returns inside hook implementations but instead call other functions if the conditions are met. 

How Do We Alter an Email?

Once all of this is in place, we have another tool at our disposal that allows us to alter such an existing setup: hook_mail_alter(). This hook is called from within the mail manager before the responsible mail plugin sends the email. The purpose is to allow other modules to perform final alterations to an existent email being sent out.

Although this can be used by other modules as well, we will illustrate an example implementation from within the same module we've been working with. To this end, we will alter the email by changing one of its default headers in order to transform it from plain text to HTML. And this is how we can do this:

As you can see, this is a simple alteration of the Content-Type header that transforms the email into HTML. This way plain text HTML entities will be parsed as HTML by mail clients. And using the switch case, we make sure this only happens for the email template we defined earlier.

One thing to note here is that the alter hook gets called after the relevant hook_mail() implementation. So after this, the only processing that happens on the email is done inside the format() method of the mail plugin (enforced by its interface).

Conclusion

And that is pretty much all there is to sending emails programatically using Drupal 8. We've seen the steps required to programatically set up email templates that get hydrated by the mail manager whenever we want it. We've also mentioned the default mail delivery plugin which is used to send emails in Drupal 8. And lastly, we've seen how other modules can now alter our email by adding new headers, changing the subject, concatenating values to the mail body, etc.

In the next article we are going to look at replacing the default PHPMail plugin with our own custom implementation. We will set up a mailer that uses Mandrill with the help of its PHP library. The goal is to allow our own module to use this mailer while the rest of the application continues to use the default PHPMailer.

Tags:

Comments

Related Articles